2013-03-31 108 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