Luis Ramos
Luis Ramos

Reputation: 529

Java GUI setting the color

I am trying to set the color for the color to red. When I run this the background stays grey. If I use the setBackground then a red background comes up but then just becomes the grey again. How can i fix this?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;


public class FinalProject extends JFrame {

private JRadioButton jrbRed = new JRadioButton("Red");

private JRadioButton jrbBlue = new JRadioButton("Blue");

public FinalProject(){

setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));

JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbRed);
jpRadioButtons.add(jrbBlue);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);

ButtonGroup color = new ButtonGroup();
color.add(jrbRed);
jrbRed.setMnemonic(KeyEvent.VK_B); 
jrbRed.setActionCommand("Red");
color.add(jrbBlue);
jrbBlue.setMnemonic(KeyEvent.VK_B);
jrbBlue.setActionCommand("Blue");

jrbRed.setSelected(true);

In the end I will use a collection of Radio Buttons to have the color of the display change to what is selected. DISCLAIMER!! This is my final project for class, I am not looking for my work to be done for me as that will hurt me in the long run. (Sorry if my grammar is bad, I just had lactic and my vision is really blurry)

Most of all Thank you for any and all comments, everything helps a person learn and i really appreciate the help for this community.

    jrbRed.addActionListener(new ActionListener() {
    @Override
    public void actionPreformed(ActionEvent e){
    JPanel.setForeground(Color.red);
}
});

Upvotes: 0

Views: 2242

Answers (2)

Reimeus
Reimeus

Reputation: 159784

Calling setBackground changes the background color on the RootPane which is not visible. Since the ContentPane is the visible child container of the frame you could do

getContentPane().setBackground(Color.RED);

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347214

Set the background of the contentPane instead of the frame.

getContentPane().setBackground(Color.RED);

Upvotes: 1

Related Questions