Reputation: 482
I have a button and 3 radio buttons in a JPanel
but the radio buttons are hidden.They should become visible when the button is clicked and I thought my ActionListener
will do that.Turns out it doesn't,when the button is clicked,all the buttons are resized to a natural size.What am I doing wrong?
Expected result/Actual result
public class Menu extends JPanel implements ActionListener{
static JPanel p =new JPanel(new GridBagLayout());
public static void Butty(){
JButton bAdd;
JRadioButton jAdd1,jAdd2,jAdd3;
ButtonGroup group = new ButtonGroup();
bAdd= new JButton("Add a new student");
bAdd.setPreferredSize(new Dimension(200,30));
jAdd1= new JRadioButton("Undergraduate Student");
jAdd1.setPreferredSize(new Dimension(200,30));
jAdd1.setSelected(true);
group.add(jAdd1);
jAdd2= new JRadioButton("Graduate Student");
jAdd2.setPreferredSize(new Dimension(200,30));
group.add(jAdd2);
jAdd3= new JRadioButton("Phd Student");
jAdd3.setPreferredSize(new Dimension(200,30));
group.add(jAdd3);
group.add(jAdd3);
p.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
p.add(bAdd,gbc);
gbc.gridy++;
p.add(jAdd1,gbc);
gbc.gridy++;
p.add(jAdd2,gbc);
gbc.gridy++;
p.add(jAdd3,gbc);
gbc.gridy++;
jAdd1.setVisible(false);
jAdd2.setVisible(false);
jAdd3.setVisible(false);
bAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
jAdd1.setVisible(true);
jAdd2.setVisible(true);
jAdd3.setVisible(true);
p.repaint();
p.revalidate();
}
});
private static void createAndShowGUI() {
JFrame frame = new JFrame("Something");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cp2=new JPanel(new BorderLayout());
JPanel main=new JPanel(new GridLayout(1, 0));
cp2.setOpaque(true);
Butty();
cp2.add(p);
main.add(cp2);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() { createAndShowGUI();}});
}
}
Upvotes: 1
Views: 73
Reputation: 482
The problem was that I had too many buttons for the size of my window.I increased the size of the window and the buttons showed up as they should.
Upvotes: 0
Reputation: 1421
Here
public void actionPerformed(ActionEvent e)
{
jAdd1.setVisible(true);
jAdd2.setVisible(true);
jAdd3.setVisible(true);
}
do this:
public void actionPerformed(ActionEvent e)
{
jAdd1.setVisible(true);
jAdd2.setVisible(true);
jAdd3.setVisible(true);
p.repaint();
p.revalidate();
}
Upvotes: 1