要實現一個簡單的畫圖板,可以使用Java的圖形庫(如Swing或JavaFX)來創建圖形界面,并使用鼠標事件和繪圖功能來實現畫圖功能。以下是一個簡單的示例代碼:
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);
});
}
}
運行以上代碼將彈出一個窗口,你可以在窗口中按下鼠標并拖動來繪制線條。當釋放鼠標時,線條將會顯示在窗口中。這只是一個簡單的示例,你可以根據需要擴展它來實現更多的繪圖功能,比如繪制不同的形狀、選擇顏色等。