📄 simpledrawboard.java
字号:
package simpledrawboard;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* 简单的画图板
*/
class SimpleDrawBoard extends JFrame implements ActionListener {
static int first = 0;
int x1,y1,x2,y2,px,py,width,hight,flag;
JRadioButton b1,b2,b3,b4,b5;
JPanel bottom;
ButtonGroup group;
public SimpleDrawBoard() {
super("Example of mouse event handling");
setBounds(100,100,450,120);
setSize(800,600);
bottom=new JPanel();
group=new ButtonGroup();
b1 = new JRadioButton("自由绘图");
b1.addActionListener(this);
group.add(b1);
bottom.add(b1);
b2 = new JRadioButton("画直线");
b2.addActionListener(this);
group.add(b2);
bottom.add(b2);
b3 = new JRadioButton("画矩形");
b3.addActionListener(this);
group.add(b3);
bottom.add(b3);
b4 = new JRadioButton("画椭圆");
b4.addActionListener(this);
group.add(b4);
bottom.add(b4);
b5 = new JRadioButton("清空");
b5.addActionListener(this);
b5.setVisible(true);
group.add(b5);
bottom.add(b5);
bottom.setVisible(true);
bottom.repaint();
add(bottom,BorderLayout.NORTH);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if(flag==1||flag==2) {
x1 = e.getX();
y1 = e.getY();
x2 = x1;
y2 = y1;
repaint();
} else if(flag==3||flag==4) {
x1 = e.getX();
y1 = e.getY();
px = x1;
py = y1;
}
}
public void mouseReleased(MouseEvent e) {
if(flag==2) {
x2 = x1;
y2 = y1;
x1 = e.getX();
y1 = e.getY();
repaint();
} else if(flag==3||flag==4) {
x2 = e.getX();
y2 = e.getY();
if(x1 > x2 || y1 > y2) {
x1 = x1 + x2;
x2 = x1 - x2;
x1 = x1 - x2;
y1 = y1 + y2;
y2 = y1 - y2;
y1 = y1 - y2;
px = x1;
py = y1;
}
width = Math.abs(x2 - px);
hight = Math.abs(y2 - py);
repaint();
}
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if(flag == 1) {
x2 = x1;
y2 = y1;
x1 = e.getX();
y1 = e.getY();
repaint();
}
}
public void mouseMoved(MouseEvent e) {
}
});
}
public void paint(Graphics g) {
if(first == 0) {
super.paint(g);
first = 1;
}
g.setColor(Color.white);
g.drawLine(0,65,800,65);
g.setColor(Color.black);
if(flag == 1 || flag == 2)
g.drawLine(x1,y1,x2,y2);
else if(flag == 3)
g.drawRect(px,py,width,hight);
else if(flag == 4)
g.drawOval(px,py,width,hight);
}
public void actionPerformed(ActionEvent e) {
try {
Graphics g=getGraphics();
if(e.getSource() == b1)
flag = 1;
else if(e.getSource() == b2)
flag = 2;
else if(e.getSource() == b3)
flag = 3;
else if(e.getSource() == b4)
flag = 4;
else if(e.getSource() == b5) {
flag = 5;
g.clearRect(0,66,800,534);
}
} catch(Exception event) {
}
}
public static void main(String [] args) {
JFrame f = new SimpleDrawBoard();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -