0

I have 2 panels in my frame, 1 is for buttons (I want to use radioButton, but for now it is easier using buttons) and the other one is for the card layout panel. My plan is to shuffle the chad when I press specific button. Like the move button will show me the move panel card. Move panel card has x0 label and text field, Line panel card has x0 and x1 both label and text field.

There are 2 classes, 1 is for the buttonpanel = Buttons the other one is for the cards = PanelMiddle Here's my code:

public class PanelMiddle{
    JPanel controlPanel = new JPanel();
    CardLayout cl = new CardLayout();

    JPanel movePanel = new JPanel();
    JPanel linePanel = new JPanel();

    JLabel x0Label = new JLabel("x0");
    JTextField x0TextField = new JTextField(3);
    JLabel x1Label = new JLabel("x1");
    JTextField x1TextField = new JTextField(3);

    public PanelMiddle(){
        controlPanel.setLayout(cl);

        //move panel
        movePanel.setLayout(new GridLayout (1,2));
        movePanel.add(x0Label);
        movePanel.add(x0TextField);
        controlPanel.add(movePanel,"Move"); //add the keyword Move to show the move card

        //line panel
        linePanel.setLayout(new GridLayout (2,2));
        //linePanel.add(x0Label);
        linePanel.add(x1Label);
        //linePanel.add(x0TextField);
        linePanel.add(x1TextField);
        controlPanel.add(linePanel,"Line"); // add the keyword Line to show the line card

        }
    }

In the other class I have:

    public class Buttons extends PanelMiddle{
    JPanel buttonPanel = new JPanel();

    JButton moveB = new JButton ("Move");
    JButton lineB = new JButton ("Line");

    public Buttons(){
    buttonPanel.setLayout(new GridLayout (2,1));
    buttonPanel.add(moveB);
    buttonPanel.add(lineB);

    action();
    }

    public void action(){
    moveB.addActionListener((e) -> {
    cl.show(controlPanel,"Move");
    });

    lineB.addActionListener((e) -> { cl.show(controlPanel,"Line");});
    }
    }

The result that I got is weird. It doesn't show fully my panel. But when I tried commenting all the line panel, it works. Does someone have a fix here?

NB: Im sorry I dont know how to edit the text here so its a little bit messy.

edit 1 : as guleryuz says, I commented out the x0Label and x0TextField from the line panel

1 Answers1

1

in swing component hierarchy a component can only be added to one container, you are adding x0Label and x0TextField two both panels. so when you add x0Labe two second panel (linePanel) it will be removed from movePanel (same case for x0TextField) so movePanel becomes empty.

more details here

Community
  • 1
  • 1
guleryuz
  • 2,714
  • 1
  • 15
  • 19