我刚开始使用 Java Graphics,我写了两个类:
/*Paintr.java file*/
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import java.util.Random;
public class Paintr extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
Random gen = new Random();
g.setColor(new Color(gen.nextInt(256),gen.nextInt(256),gen.nextInt(256)));
g.fillRect(15, 25, 100, 20);
g.drawString("Current color: "+ g.getColor(),130,65);
}
}
主要课程:
import javax.swing.JFrame;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing stuff.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Paintr board = new Paintr();
frame.add(board);
frame.setSize(400, 300);
frame.setResizable(true);
frame.setVisible(true);
}
}
现在,如果我编译并运行它,它就可以工作。它显示我的随机颜色。我不明白为什么在我调整 Frame 大小后它会改变显示的颜色。为什么会想起这段代码:
g.setColor(new Color(gen.nextInt(256),gen.nextInt(256),gen.nextInt(256)));
g.fillRect(15, 25, 100, 20);
g.drawString("Current color: "+ g.getColor(),130,65);