要实现一个简单的画图板,可以使用Java的图形库(如Swing或JavaFX)来创建图形界面,并使用鼠标事件和绘图功能来实现画图功能。以下是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DrawingBoard extends JFrame {
private int startX, startY, endX, endY;
public DrawingBoard() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
JPanel drawingPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(startX, startY, endX, endY);
}
};
drawingPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
drawingPanel.repaint();
}
});
getContentPane().add(drawingPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DrawingBoard drawingBoard = new DrawingBoard();
drawingBoard.setVisible(true);
});
}
}
```
运行以上代码将弹出一个窗口,你可以在窗口中按下鼠标并拖动来绘制线条。当释放鼠标时,线条将会显示在窗口中。这只是一个简单的示例,你可以根据需要扩展它来实现更多的绘图功能,比如绘制不同的形状、选择颜色等。