我剛開始使用Java的圖形工作的顏色,我寫了兩個類:調整大小的Java JFrame的變化的圖形組件
/*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);
}
}
現在,如果我編譯這並運行,它的工作原理。它顯示我的隨機顏色。我不明白的是爲什麼在調整幀大小後,它會改變顯示的顏色。爲什麼它會回憶這段代碼:
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);
如果您不希望發生這種情況,請考慮將隨機顏色繪製到BufferedImage,然後在'paintComponent(...)'方法中繪製該顏色。 –