I am trying to make a java program like the guy in a video i watched. He made a menu with a button group to change the background color of the frame. the code i have is like this:
But whenever I run it the background is always green. Can anyone correct this to make it work right?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class color extends JFrame implements ActionListener {
private JMenuBar bar;
private JMenu menu;
private JRadioButtonMenuItem red;
private JRadioButtonMenuItem blue;
private JRadioButtonMenuItem green;
public color() {
bar = new JMenuBar();
menu = new JMenu("Colors");
red = new JRadioButtonMenuItem("Red");
blue = new JRadioButtonMenuItem("Blue");
green = new JRadioButtonMenuItem("Green");
setLayout(new FlowLayout());
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Colors");
bar.add(menu);
menu.add(red);
menu.add(blue);
menu.add(green);
ButtonGroup group = new ButtonGroup();
group.add(red);
group.add(blue);
group.add(green);
red.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
add(bar);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == red) {
setBackground(Color.RED);
}
if (e.getSource() == blue) {
setBackground(Color.BLUE);
}
if (e.getSource() == green); {
setBackground(Color.GREEN);
}
}
}
But whenever I run it the background is always green. Can anyone correct this to make it work right?
Last edited by a moderator: