java - 随机颜色背景

标签 java swing graphics keylistener paintcomponent

我试图让这段代码在我按“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();
    }
}

最佳答案

我首先从 paintComponent 方法中删除 setBackground(Color.BLACK);

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

(int)Math.random() * 256

这基本上是将 Math.random() 的结果转换为 int,这通常会导致它变成 0 ,然后乘以 256,即 0...

相反,尝试使用类似的东西

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

它将在将结果转换为 int 之前执行 Math.random() * 256 的计算

您可能还想查看Frame#getExtendedStateFrame#setExtendedState ...这将使您的生活变得更加轻松...

关于java - 随机颜色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237077/

相关文章:

java - 如何自动调整 JTree 对象的大小?

java - jPanel 调整大小后 jScrollPane 滚动消失

java - 加载栏不重画java

java - 如何在paintComponent中自动添加形状?

java - 没有找到主类?网 bean

javascript - 如何在 three.js 中从 BufferGeometry 绘制 2D/3D 网格

java - 丰富的动态分页 :dataTable/rich:datascroller with large datasets

java - 如何将 html 页面(JSP)中选定的信息发送到 servlet?

java - NamedEntityGraph - JPA/Hibernate 抛出 org.hibernate.loader.MultipleBagFetchException : cannot simultaneously fetch multiple bags

Java 在 if 语句处终止,退出值 0