Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

Navigate Between JPanels?

I have a problem when I click a button to change the content of right_pan(JPanel) nothing happens; I have 3 JPanel: pan_glob therein lies the other two: right_pan and left_pan(are integrated into the main JFrame named "main" see screenshot),and another external JPanel named cree_client (contains text box).

enter image description here

I'd like when I click a button, the content of cree_client(JPanel) is loaded into right_pan(JPanel).

I tried this but it does not work :

  private void jMenuItem23ActionPerformed(java.awt.event.ActionEvent evt) {

  cree_client cc=new cree_client();
  this.right_pan.removeAll();
  this.right_pan.validate();
  this.right_pan.add(cc);
  this.right_pan.revalidate();

}

ANY helps ?

Upvotes: 0

Views: 951

Answers (2)

chubbsondubs
chubbsondubs

Reputation: 38852

First rule of using any UI toolkit: don't remove/add children to control visibility. It never works very well in almost any UI toolkit. It requires more work on the toolkit to properly handle it, and that goes double for Swing. Instead use either visibility, or I bet what you should use is a CardLayout. A panel with a CardLayout will allow you to flip between several screens:

public class StackPanel extends JPanel {

    CardLayout layout = new CardLayout();
    public StackPanel() {
        super();
        setLayout( layout );
    }

    public addStack( String name, JComponent child ) {
        add( name, child );
    }

    public void showStack( String name ) {
        layout.show( this, name );
    }
}


CardLayout layout = new CardLayout();
StackPanel stack = new StackPanel();
stack.addStack( "panelOne", panelOne );
stack.addStack( "panelTwo", panelTwo );
...
JButton someButton = new JButton( new AbstractAction("Next" ) {
    public void actionPerformed(ActionEvent evt ) {
       stack.showStack( "panelTwo" );
    }
} );

If you don't want to flip between two or more screens, then you can use setVisible() to hide and show the different screens just as well.

Upvotes: 2

Andy
Andy

Reputation: 3692

First of all, have you actually checked that the code in your action listener is being performed? I'm not that familiar with JMenus but I think that method should be more like

public void ActionPerformed(ActionEvent evt){...}

and the action listener should be added to JMenuItem itself - a quick System.out.println() statement in the body of the action performed method should help you determine whether the code to change the JPanel is executing or not!

Secondly, if your actionPerformed method is running you may want to try running the Component.repaint() method after you revalidate. Also, it may be a thought to try 'revalidating' and 'repainting' the main JPanel that houses the one you are changing (in your case the parent of right_pan)!

Upvotes: 0

Related Questions