Reputation: 87
I am trying to get this code to change the background color to a random color when I press 'r'. So far everything is working ok other than changing the background color to a random color. This program is a screen saver that I have to generate random shapes in random positions with random colors.
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();
}
}
Upvotes: 0
Views: 3440
Reputation: 33
Try this:
(int)(Math.random() * 256)
Or this:
Random gen= new Random();
getContentPane().setBackground(Color.Black);
To get random colors, try this:
.setBackground(Color.(gen.nextInt(256), gen.nextInt(256),
gen.nextInt(256));
Upvotes: 0
Reputation: 347214
I would start by removing setBackground(Color.BLACK);
from your paintComponent
method
The other problem you're having is with the way you are calculating your random values...
(int)Math.random() * 256
This is basically casting the result of Math.random()
to an int
, which will, typically, result in it becoming 0
, before it's multiplied by 256
, which is 0
...
Instead, try using something like
(int)(Math.random() * 256)
Which will perform the calculation of Math.random() * 256
before casting the result to int
You may also want to take a look at Frame#getExtendedState
and Frame#setExtendedState
...it will make your life considerably eaiser...
Upvotes: 4