在GUI上添加东西的3种方法:
1.在frame上放置widget:
frame.getContentPane().add(widget);
2.在widget上绘制2D图形;
3.在widget上绘制JPEG图。
2与3均使用graphics对象来绘制图;
创建出自己的widget,并将其放到frame上
创建JPanel的子类,并且重写paintComponent()这个方法
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
//设置颜色:
g.setColor(Color.orange);//设为orange的颜色
//设置随机颜色:
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);
//画矩形:
g.fillRect(20, 50, 100, 100);
//参数分别起始X坐标,起始Y坐标,宽度,高度。
//画椭圆:
g.fillOval(20,50,100,100)
//参数分别起始X坐标,起始Y坐标,X轴长度,Y轴长度。
测试代码:
public static void main(String[] args) {
JFrame frame = new JFrame();
MyDrawPanel myDraw = new MyDrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(myDraw);
frame.setSize(300, 300);
frame.setVisible(true);
}
效果:生成orange的矩形框
随机生成颜色:理论上来说每次都不一样
public void paintComponent(Graphics g) {
Image image = new ImageIcon("JPEG图像名").getImage();
g.drawImage(image, 3, 4, this);
}
public void paintComponent(Graphics g)
参数g是个Graphics对象,但是实际所引用的时Graphics的子类Graphics2D(多态)。
Graphics2D在Graphics的基础上实现其他的功能,但是以Graphics对象声明的g无法使用,因此需要对g进行转换:
Graphics2D g2d = (Graphics2D) g;
public class ChangeColor {
JFrame frame;
JButton button;
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Button");
button.addActionListener((ActionListener) new Button());
MyDrawPanel myDraw = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, myDraw);
frame.setSize(300, 300);
frame.setVisible(true);
}
class Button implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
public static void main(String[] args) {
ChangeColor tb = new ChangeColor();
tb.go();
}
}
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color randomColor = new Color(red,green,blue);
g.setColor(randomColor);
g.fillRect(20, 50, 100, 100);
}
}