0

I am trying to programmatically change my layout when something is clicked. However, when one layout is visible, and I attempt to change it (via an ActionListener), both layouts are present, instead of only the new, desired one.

borderLayout.addActionListener(new ActionListener() {

   @Override
   public void actionPerformed(ActionEvent e) {
       setBorderLayout();
   }

});

flowLayout.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {      
        settingFlowLayout();
    }

});

Here are the methods:

private void setBorderLayout() {
    getContentPane().setLayout(null);
    setLayout(new BorderLayout(3, 3));
    b1 = new JButton("NORTH");
    add(b1, BorderLayout.NORTH);
    b2 = new JButton("SOUTH");
    add(b2, BorderLayout.SOUTH);
    b3 = new JButton("CENTER");
    add(b3, BorderLayout.CENTER);
    b4 = new JButton("EAST");
    add(b4, BorderLayout.EAST);
    b5 = new JButton("WEST");
    add(b5, BorderLayout.WEST);
    setVisible(true);

}

// Setting Flow Layout
private void settingFlowLayout() {

    getContentPane().setLayout(null);
    setLayout(new FlowLayout());
    btn1 = new JButton("Button 1");
    add(btn1);
    btn2 = new JButton("This is Button 2");
    add(btn2);
    btn3 = new JButton("3");
    add(btn3);
    btn4 = new JButton("Another Button 4");
    add(btn4);
    btn5 = new JButton("Button 5");
    add(btn5);
    btn6 = new JButton("One More Button 6");
    add(btn6);

    setVisible(true);
}

What can I do so that I can only see one layout instead of both?

xes_p
  • 501
  • 4
  • 14
  • 1
    Try calling validate() and repaint() methods it might fix the issue. – DonatasD Jun 03 '16 at 20:06
  • at fist set all the layouts to setVisible(false). When you clicked and item then set the corresponding layout to setVisible(true).If you again clicked a different one then set the previous layout as setVisible(false) and corresponding layout as setVisible(true); – Rahal Kanishka Jun 03 '16 at 20:06
  • 1
    [How to Use CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) – MadProgrammer Jun 03 '16 at 21:26
  • Better to use `CardLayout`, but `validate()` is an alternative, for [example](http://stackoverflow.com/a/5751044/230513). – trashgod Jun 03 '16 at 22:16

1 Answers1

0

Well, not sure what you're asking, but you might want to try to create 2 JPanels, have different layouts for each one, add your componenets on them, and change the content pane of the JFrame when you click the button. Hope it helps