2013-10-08 149 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

請考慮格式化你的答案,這對我來說並不完全可讀。 –