注释很详细,直接上代码……
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class swing_test_18 {
//定义一下矩形和椭圆的类型名称
private final String RECT_SHAPE = "rect";//矩形
private final String OVAL_SHAPE = "oval";//椭圆
private Frame frame=new Frame("绘图测试");
Button btn_rect=new Button("绘制矩形");
Button btn_oval=new Button("绘制椭圆");
//定义一个变量,记录当前绘制的图形类型
private String shape="";
//自定义类,继承Canvas类,重写paint(Graphics g)方法完成画图
private class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
if(shape.equals(RECT_SHAPE)) {
//绘制矩形
g.setColor(Color.BLACK);// 设置画笔颜色为黑色
g.drawRect(100, 100, 150, 100);
} else if(shape.equals(OVAL_SHAPE)) {
//绘制椭圆
g.setColor(Color.RED); // 设置画笔颜色为红色
g.drawOval(100, 100, 150, 100);
};
}
}
//创建自定义的画布对象
private MyCanvas canvas=new MyCanvas();
//组装视图
private void init() {
//添加按钮事件监听器
btn_rect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shape=RECT_SHAPE;//设置当前绘制图形类型为矩形
canvas.repaint();//刷新画布
}
});
//添加按钮事件监听器
btn_oval.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shape=OVAL_SHAPE;//设置当前绘制图形类型为椭圆
canvas.repaint();//刷新画布
}
});
//创建Panel面板,承载按钮
Panel panel=new Panel();
panel.add(btn_rect);
panel.add(btn_oval);
//添加面板
frame.add(panel,BorderLayout.SOUTH);
//设置drawer的大小
canvas.setSize(300,300);
//或canvas.setPreferredSize(new Dimension(300,300));
frame.add(canvas,BorderLayout.CENTER);//添加画布
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//启动程序
new swing_test_18().init();
}
}
运行效果: