简体   繁体   中英

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

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

设置contentPane的背景而不是框架。

getContentPane().setBackground(Color.RED);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM