Java实现白板程序的代码
时间: 2024-03-23 20:40:29 浏览: 85
java白板代码
以下是一个简单的Java白板程序的代码示例:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Whiteboard extends JFrame {
private JPanel canvas;
private int startX, startY, endX, endY;
private Color currentColor;
private int currentSize;
public Whiteboard() {
setTitle("Whiteboard");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
canvas = new JPanel();
canvas.setBackground(Color.WHITE);
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
});
canvas.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
Graphics2D g = (Graphics2D) canvas.getGraphics();
g.setColor(currentColor);
g.setStroke(new BasicStroke(currentSize));
g.drawLine(startX, startY, endX, endY);
startX = endX;
startY = endY;
}
});
add(canvas, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem openItem = new JMenuItem("Open");
saveItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Implement save functionality here
}
});
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Implement open functionality here
}
});
fileMenu.add(saveItem);
fileMenu.add(openItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
JButton pencilButton = new JButton(new ImageIcon("pencil.png"));
pencilButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentColor = Color.BLACK;
currentSize = 2;
}
});
JButton lineButton = new JButton(new ImageIcon("line.png"));
lineButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentColor = Color.RED;
currentSize = 4;
}
});
toolBar.add(pencilButton);
toolBar.add(lineButton);
add(toolBar, BorderLayout.NORTH);
}
public static void main(String[] args) {
Whiteboard whiteboard = new Whiteboard();
whiteboard.setVisible(true);
}
}
```
这个代码示例创建了一个带有绘图面板、菜单和工具栏的Java白板程序。它使用了Java的Swing库来创建GUI组件和事件监听器,并使用了Graphics2D类来绘制基本形状。你可以根据自己的需求对代码进行修改和扩展。
阅读全文