public class Drawboard extends JFrame{
Graphics g;
public static void main(String[] args){
Drawboard d = new Drawboard();
d.showUI();
}
public void showUI(){
Graphics g ;
this.setTitle("画图板");
this.setSize(600,600);
this.setDefaultCloseOperation(3);
this.setResizable(false);
java.awt.FlowLayout fl = new java.awt.FlowLayout();
this.setLayout(fl);
JPanel p = new JPanel();
this.add(p);
// 创建一个面板
p.setPreferredSize(new Dimension(550,400));
// 设置面板颜色
p.setBackground(Color.green);
JRadioButton jr1 =new JRadioButton("line");
jr1.setActionCommand("直线");
JRadioButton jr2 =new JRadioButton("rectangle");
jr2.setActionCommand("矩形");
JRadioButton jr3 =new JRadioButton("圆角矩形");
jr3.setActionCommand("圆角矩形");
JRadioButton jr4 =new JRadioButton("eclipse");
jr4.setActionCommand("椭圆");
JRadioButton jr5 =new JRadioButton("fill the rectangle");
jr5.setActionCommand("填充矩形");
JRadioButton jr6 =new JRadioButton("填充椭圆");
jr6.setActionCommand("填充椭圆");
JRadioButton jr7 =new JRadioButton("圆弧");
jr7.setActionCommand("圆弧");
//创建一个group(这是个容器),并把所有单选对象放进去
ButtonGroup group = new ButtonGroup();
group.add(jr1);
group.add(jr2);
group.add(jr3);
group.add(jr4);
group.add(jr5);
group.add(jr6);
group.add(jr7);
this.add(jr1);
this.add(jr2);
this.add(jr3);
this.add(jr4);
this.add(jr5);
this.add(jr6);
this.add(jr7);
this.setVisible(true);
//创建一个画布
g = this.getGraphics();
//创建鼠标监听器对象
mouselistener lis = new mouselistener(g,group);
this.addMouseListener(lis);
}
}
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ButtonGroup;
public class mouselistener implements MouseListener {
int x1,x2,y1,y2;
private Graphics g;
public String command;
ButtonGroup group;
public mouselistener(Graphics g,ButtonGroup group){
this.g = g;
this.group = group;
}
//鼠标按键在组件上按下时调用
public void mousePressed(MouseEvent e){
x1=e.getX();
y1=e.getY();
}
//鼠标按钮在组件上释放时调用。
public void mouseReleased(MouseEvent e){
x2=e.getX();
y2=e.getY();
String command = group.getSelection().getActionCommand();
if("直线".equals(command))
//画直线
g.drawLine(x1, y1, x2, y2);
else if("矩形".equals(command))
//绘制矩形
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1));
else if("椭圆".equals(command))
//绘制椭圆
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1));
else if("填充矩形".equals(command))
//填充矩形
g.fillRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1));
else if("圆角矩形".equals(command))
//圆角矩形
g.drawRoundRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1),12,12);
else if("填充椭圆".equals(command))
//填充椭圆
g.fillOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1));
else if("圆弧".equals(command))
//画圆弧
g.drawArc(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2-x1), Math.abs(y2-y1),45,90);
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}