2013-03-31 42 views
1

我剛開始使用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); 
+0

如果您不希望發生這種情況,請考慮將隨機顏色繪製到BufferedImage,然後在'paintComponent(...)'方法中繪製該顏色。 –

回答

3

每次調整幀大小時都調用paintComponent()函數。這是爲了讓開發人員調整其他的東西來適應新的尺寸!

如果你不希望出現這種情況定義顏色作爲變量

Color color = new Color(gen.nextInt(256),gen.nextInt(256),gen.nextInt(256)); 

然後在你的paintComponent()功能只是油漆的顏色。

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    this.setBackground(Color.WHITE); 
    g.setColor(color); 
    g.fillRect(15, 25, 100, 20); 
    g.drawString("Current color: "+ g.getColor(),130,65); 
} 
+0

謝謝。現在有道理。 – Bogdan

+2

很高興我能幫忙:) – Kezz101