/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package simpledraw;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
/**
*
* @author 91152
*/
public class SimpleDraw {
private final String RECT_SHAPE = "rect";
private final String OVAL_SHAPE = "oval";
private JFrame jf = new JFrame("简单绘图");
private JButton rect = new JButton("绘制矩形");
private JButton oval = new JButton("绘制圆形");
private MyCanvas drawArea = new MyCanvas();
private String shape = "";
public void init(){
JPanel p = new JPanel();
p.add(rect);
p.add(oval);
rect.addActionListener(event ->{
shape = RECT_SHAPE;
drawArea.repaint();
});
oval.addActionListener(event ->{
shape = OVAL_SHAPE;
drawArea.repaint();
});
//下面肯定是为了pack()的原因
drawArea.setPreferredSize(new Dimension(250,180));
jf.add(drawArea);
jf.add(p,BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args) {
new SimpleDraw().init();
}
class MyCanvas extends Canvas{
public void paint(Graphics g){
Random rand = new Random();
if(shape.equals(RECT_SHAPE)){
g.setColor(new Color(220,100,80));
g.drawRect(rand.nextInt(200), rand.nextInt(120), 40, 60);
}
if(shape.equals(OVAL_SHAPE)){
g.setColor(new Color(80,100,200));
g.fillOval(rand.nextInt(200), rand.nextInt(120), 50, 40);
}
}
}
}