2013-10-08 152 views
0

我想要得到这个代码,当我按下'r'时,将背景颜色更改为随机颜色。到目前为止,除了将背景颜色更改为随机颜色之外,一切工作都正常。这个程序是一个屏幕保护程序,我必须随机产生颜色随机的随机形状。随机颜色背景

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.Random; 

public class ScreenSaver1 extends JPanel { 
    private JFrame frame = new JFrame("FullSize"); 
    private Rectangle rectangle; 
    boolean full; 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     setBackground(Color.BLACK); 
    } 

    ScreenSaver1() { 
     // Remove the title bar, min, max, close stuff 
     frame.setUndecorated(true); 
     // Add a Key Listener to the frame 
     frame.addKeyListener(new KeyHandler()); 
     // Add this panel object to the frame 
     frame.add(this); 
     // Get the dimensions of the screen 
     rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment() 
     .getDefaultScreenDevice().getDefaultConfiguration().getBounds(); 
     // Set the size of the frame to the size of the screen 
     frame.setSize(rectangle.width, rectangle.height); 
     frame.setVisible(true); 
     // Remember that we are currently at full size 
     full = true; 
    } 

// This method will run when any key is pressed in the window 
class KeyHandler extends KeyAdapter { 
    public void keyPressed(KeyEvent e) { 
     // Terminate the program. 
     if (e.getKeyChar() == 'x') { 
      System.out.println("Exiting"); 
      System.exit(0); 
     } 
     else if (e.getKeyChar() == 'r') { 
      System.out.println("Change background color"); 
      setBackground(new Color((int)Math.random() * 256, (int)Math.random() * 256, (int)Math.random() * 256)); 
     } 
     else if (e.getKeyChar() == 'z') { 
      System.out.println("Resizing"); 
      frame.setSize((int)rectangle.getWidth()/2, (int)rectangle.getHeight()); 
     } 
    } 

} 

public static void main(String[] args) { 
     ScreenSaver1 obj = new ScreenSaver1(); 
    } 
} 

回答

4

我会从你的paintComponent方法去除setBackground(Color.BLACK);开始

您遇到的另一个问题是,你正在计算随机值的方式......

(int)Math.random() * 256 

这是基本上将Math.random()的结果投射到int,这通常会导致它变成0,在它乘以256之前,即0 ...

相反,尝试使用类似

(int)(Math.random() * 256) 

这将结果铸造int

你也可能想看看Frame#getExtendedStateFrame#setExtendedState之前执行的Math.random() * 256计算...它会让你的生活变得更加有趣...

+0

我忘了重绘()。我只是使用setBackground(Color.BLACK)作为测试。当我这样做时,它只会从白色变为黑色。 – Ryel

+0

@Rel看更新... – MadProgrammer

+0

这也是有道理的。这就是它变黑的原因。 – Ryel

0

试试这个:

(int)(Math.random() * 256) 

或者这样:

Random gen= new Random(); 
getContentPane().setBackground(Color.Black); 

要获得随机颜色,试试这个:

.setBackground(Color.(gen.nextInt(256), gen.nextInt(256), 
       gen.nextInt(256)); 
+0

请考虑格式化你的答案,这对我来说并不完全可读。 –