My code simply displays a random colour and has a button to get a new one but how could I make the ActionListener
respond to pressing Enter as well?
Also, how can I make the button not fill the whole width of the JFrame
?
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RandomColour {
public static JFrame frame;
public static Color[] colours = {Color.RED, Color.YELLOW, Color.ORANGE, Color.BLUE, Color.GREEN, Color.BLACK, Color.MAGENTA, Color.CYAN, Color.PINK,};
public static int random;
public static void main(String[] args) {
random = (int)(Math.random()*(9)+0);
JButton button = new JButton ("New Random Colour");
button.setSize(10, 10);
frame = new JFrame ("Random Colour");
JPanel panel = new JPanel(new GridLayout(6,6,6,6));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(colours[(int)(Math.random()*(9)+0)]);
}
});
panel.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(500, 500);
frame.setContentPane(panel);
frame.getContentPane().setBackground(colours[random]);
frame.setLocationRelativeTo(null);
}
}