I want to create an application where pressing a button changes the background color, but I don't know why the color won't change. I can't change it at all. Swapping the button color and its font works, but I can't change the background color.
package okno;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class Kolory extends JFrame implements ActionListener {
static JButton FirstButton;
Color [] colors= {Color.GREEN,Color.RED,Color.BLACK};
JLayeredPane screen;
public Kolory() {
super("Zmiana kolorów");
screen = new JLayeredPane();
getContentPane().add(screen).setBackground(Color.RED);;
screen.setPreferredSize(new Dimension(500,500));
FirstButton = new JButton("Pierwszy przycisk");
screen.add(FirstButton);
FirstButton.setBounds(30, 30, 150, 20);
FirstButton.addActionListener(this);
}
public static void main(String[] args) {
JFrame frame = new Kolory();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.pack();
}
@Override
public void actionPerformed(ActionEvent e) {
Random r = new Random();
int counter = r.nextInt(3);
screen.setBackground(colors[counter]);
}
}