要實(shí)現(xiàn)Java畫圖板,可以使用Java Swing庫來創(chuàng)建圖形用戶界面(GUI),并使用Java Graphics2D類來繪制圖形。
以下是一個(gè)簡單的Java畫圖板的實(shí)現(xiàn)示例:
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);
});
}
}
這只是一個(gè)基本的示例,你可以根據(jù)自己的需求進(jìn)一步擴(kuò)展和改進(jìn)。例如,你可以添加更多的繪圖工具(如矩形、橢圓、文本等),以及實(shí)現(xiàn)撤銷、保存等功能。