0

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]);
    
}

}
  • Does this answer your question? [How to set a background color on a JLayeredPane?](https://stackoverflow.com/questions/4480196/how-to-set-a-background-color-on-a-jlayeredpane) – maloomeister Feb 18 '21 at 11:44
  • TL;DR from the duplicate link: Set the `JLayeredPane` opaque via `screen.setOpaque(true);` beforehand. – maloomeister Feb 18 '21 at 11:45
  • 1
    Please learn common Java nomenclature (naming conventions - e.g. `EachWordUpperCaseClass`, `firstWordLowerCaseMethod()`, `firstWordLowerCaseAttribute` unless it is an `UPPER_CASE_CONSTANT`) and use it consistently. – Andrew Thompson Feb 18 '21 at 12:22

0 Answers0