要實現一個簡單的畫圖板功能,你可以使用Java的Swing庫來實現。下面是一個簡單的示例代碼,可以實現畫圖板的基本功能:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DrawingBoard extends JFrame {
private JPanel canvas;
private int prevX, prevY;
public DrawingBoard() {
canvas = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
};
canvas.setBackground(Color.WHITE);
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
}
});
canvas.addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Graphics g = canvas.getGraphics();
g.drawLine(prevX, prevY, x, y);
prevX = x;
prevY = y;
}
});
add(canvas);
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DrawingBoard();
}
});
}
}
在這個示例中,我們創建了一個繼承自JFrame的DrawingBoard類,它包含一個JPanel作為畫布來繪制圖形。我們通過添加鼠標事件監聽器來實現繪圖功能。當鼠標按下時記錄當前坐標,當鼠標拖動時在畫布上繪制直線,并更新prevX和prevY的值。
你可以在以上代碼的基礎上進行擴展,實現更復雜的畫圖功能,比如繪制不同形狀的圖形、選擇不同的畫筆顏色和粗細、保存繪制的圖形等。