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

2 に答える 2

4

私はsetBackground(Color.BLACK);あなたのpaintComponent方法から削除することから始めます

あなたが抱えている他の問題は、ランダムな値を計算する方法にあります...

(int)Math.random() * 256

Math.random()これは基本的に の結果をにキャストしますint。これは通常、 を0掛ける前に になります。256これは0...

代わりに、次のようなものを使用してみてください

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

Math.random() * 256結果をキャストする前に計算を実行しますint

Frame#getExtendedStateあなたも見てみたいと思うかもしれませんFrame#setExtendedState...それはあなたの人生をかなり楽にします...

于 2013-10-08T00:23:35.690 に答える