java画图_Java实现的简单画图板示例
时间: 2024-03-07 15:49:06 浏览: 50
好的,下面是一个简单的 Java 画图板示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimplePaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
private JButton clearBtn, blackBtn, blueBtn, greenBtn, redBtn;
private JLabel mousePos;
private JPanel drawPanel;
private int prevX, prevY, currX, currY;
public SimplePaint() {
super("Simple Paint");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建按钮
clearBtn = new JButton("Clear");
blackBtn = new JButton("Black");
blueBtn = new JButton("Blue");
greenBtn = new JButton("Green");
redBtn = new JButton("Red");
// 设置按钮监听器
clearBtn.addActionListener(this);
blackBtn.addActionListener(this);
blueBtn.addActionListener(this);
greenBtn.addActionListener(this);
redBtn.addActionListener(this);
// 创建面板
JPanel btnPanel = new JPanel();
btnPanel.add(clearBtn);
btnPanel.add(blackBtn);
btnPanel.add(blueBtn);
btnPanel.add(greenBtn);
btnPanel.add(redBtn);
mousePos = new JLabel("Mouse position: ");
drawPanel = new JPanel();
drawPanel.setBackground(Color.white);
drawPanel.addMouseListener(this);
drawPanel.addMouseMotionListener(this);
add(btnPanel, BorderLayout.NORTH);
add(mousePos, BorderLayout.SOUTH);
add(drawPanel, BorderLayout.CENTER);
setSize(600, 400);
setVisible(true);
}
// 按钮事件处理
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearBtn) {
Graphics g = drawPanel.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, drawPanel.getWidth(), drawPanel.getHeight());
} else if (e.getSource() == blackBtn) {
drawPanel.setForeground(Color.black);
} else if (e.getSource() == blueBtn) {
drawPanel.setForeground(Color.blue);
} else if (e.getSource() == greenBtn) {
drawPanel.setForeground(Color.green);
} else if (e.getSource() == redBtn) {
drawPanel.setForeground(Color.red);
}
}
// 鼠标事件处理
public void mousePressed(MouseEvent e) {
prevX = e.getX();
prevY = e.getY();
}
public void mouseDragged(MouseEvent e) {
currX = e.getX();
currY = e.getY();
Graphics g = drawPanel.getGraphics();
g.drawLine(prevX, prevY, currX, currY);
prevX = currX;
prevY = currY;
}
public void mouseClicked(MouseEvent e) {
mousePos.setText("Mouse position: " + e.getX() + ", " + e.getY());
}
public void mouseMoved(MouseEvent e) {
mousePos.setText("Mouse position: " + e.getX() + ", " + e.getY());
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new SimplePaint();
}
}
```
这个简单的画图板示例包含了颜色选择、清除以及鼠标事件处理等基本功能。你可以根据自己的需求进行修改和扩展。
阅读全文