要實現Java畫圖板,可以使用Java Swing庫來創建圖形用戶界面(GUI),并使用Java Graphics2D類來繪制圖形。
以下是一個簡單的Java畫圖板的實現示例:
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 Point startPoint;
public DrawingBoard() {
setTitle("Java畫圖板");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
canvas = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
};
canvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
}
});
canvas.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2d = (Graphics2D) canvas.getGraphics();
g2d.drawLine(startPoint.x, startPoint.y, e.getX(), e.getY());
startPoint = e.getPoint();
}
});
getContentPane().add(canvas);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DrawingBoard drawingBoard = new DrawingBoard();
drawingBoard.setVisible(true);
});
}
}
這只是一個基本的示例,你可以根據自己的需求進一步擴展和改進。例如,你可以添加更多的繪圖工具(如矩形、橢圓、文本等),以及實現撤銷、保存等功能。