我想要得到这个代码,当我按下'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();
}
}
我忘了重绘()。我只是使用setBackground(Color.BLACK)作为测试。当我这样做时,它只会从白色变为黑色。 – Ryel
@Rel看更新... – MadProgrammer
这也是有道理的。这就是它变黑的原因。 – Ryel