要實現畫圖板功能,可以使用Java的Swing庫來創建一個簡單的繪圖應用。以下是一個基本的示例代碼,用于實現畫圖板功能:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DrawingBoard extends JFrame {
private int startX, startY, endX, endY;
private Color currentColor = Color.BLACK;
public DrawingBoard() {
setTitle("Drawing Board");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel controlPanel = new JPanel();
JButton redButton = new JButton("Red");
redButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentColor = Color.RED;
}
});
JButton blackButton = new JButton("Black");
blackButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentColor = Color.BLACK;
}
});
controlPanel.add(redButton);
controlPanel.add(blackButton);
JPanel drawingPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(currentColor);
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(controlPanel, BorderLayout.NORTH);
getContentPane().add(drawingPanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
DrawingBoard drawingBoard = new DrawingBoard();
drawingBoard.setVisible(true);
}
});
}
}
此代碼創建了一個簡單的繪圖板應用程序,用戶可以在畫板上繪制直線,并可以選擇繪制的顏色。用戶可以使用鼠標按下并拖動來繪制線條。您可以根據需要擴展此示例代碼,以實現更復雜的繪圖功能,如繪制不同形狀、使用不同的畫筆風格等。