Reputation: 21
I need to create a GUI that has red, green and blue radiobuttons
. When a radiobutton
is clicked they should cause a panel in the centre of the frame to change to the corresponding backcolour
colour. Here is my code below: what am I doing wrong. Here is my code below(please help; it compiles but the frame appears tiny and displays nothing):
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RadioButtons extends JFrame implements ActionListener {
JFrame f;
JPanel panel = new JPanel();
JRadioButton rb1, rb2, rb3;
JButton b1;
JButton b2;
JButton b3;
public RadioButtons() {
f = new JFrame();
rb1 = new JRadioButton("Green");
//rb1 = new JLabel(, JLabel.RIGHT);
rb1.setBounds(100, 70, 100, 40);
rb2 = new JRadioButton("Red");
rb2.setBounds(100, 90, 100, 40);
//rb2 = new JLabel("Red", JLabel.RIGHT);
rb3 = new JRadioButton("Blue");
rb3.setBounds(100, 100, 100, 40);
//rb3 = new JLabel("Blue", JLabel.RIGHT);
ButtonGroup s1 = new ButtonGroup();
s1.add(rb1);
s1.add(rb2);
s1.add(rb3);
this.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
f.setTitle("GUI Background Changer");
b1 = new JButton("Change background color");
b1.setBounds(200, 200, 50, 50);
b1.addActionListener(this);
b2 = new JButton("Change background color");
b2.setBounds(200, 200, 50, 50);
b2.addActionListener(this);
b3 = new JButton("Change background color");
b3.setBounds(200, 200, 50, 50);
b3.addActionListener(this);
add(rb1);
add(rb2);
add(rb3);
f.add(panel);
//x.setDefaultCloseOperation(XFrame.EXIT_ON_CLOSE);
}//constructor
public static void main(String[] args) {
RadioButtons radiobuttons = new RadioButtons();
radiobuttons.setJpanelSize(200, 200, 50, 50);//setJPanelSize(200,200,50,50);
radiobuttons.setDefaultCloseOperation(EXIT_ON_CLOSE);
}// main
public void backgroundChanged(ActionEvent e) {
Color initialcolor1 = Color.RED;
Color initialcolor2 = Color.BLUE;
Color initialcolor3 = Color.GREEN;
if (rb1.isSelected()) {
panel.setBackground(initialcolor1);
}// if
else
if (rb2.isSelected()) {
panel.setBackground(initialcolor2);
}// else if
else {
panel.setBackground(initialcolor2);
}// else
}
public void setJpanelSize(int v, int w, int x, int y) {
}// setJPanel size
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}//class
Upvotes: 1
Views: 49
Reputation: 17454
it compiles but the frame appears tiny and displays nothing):
That is probably because you forgot to pack
your JFrame after adding the components. Invoke pack()
for your frame after adding the components.
You will also want to:
setVisible(true)
after all other actions.Upvotes: 1