Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To achieve such things you need to use <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html" rel="nofollow">CardLayout</a>. </p> <p>Moreover, Once you remove the old JPanel from the JFrame to add a new JPanel, always do revalidate() and repaint() on the JFrame to realize the changes. Do remember, that only one component can be added at any given time at any given location. Try this code with modifications : </p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelTest { public PanelTest() { JButton b1 = new JButton("show p1"); JButton b2 = new JButton("show p2"); JLabel l1 = new JLabel("This is p1"); JLabel l2 = new JLabel("This is p2"); final JPanel p1 = new JPanel(new FlowLayout()); p1.add(l1); final JPanel p2 = new JPanel(new FlowLayout()); p2.add(l2); JPanel buttonPNL = new JPanel(new FlowLayout()); buttonPNL.add(b1); buttonPNL.add(b2); final JFrame frm = new JFrame(); // shifted this line here. b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ // Added by me , these three lines if (p2.isShowing()) { frm.remove(p2); frm.add(p1, BorderLayout.CENTER); frm.revalidate(); // for JDK 1.7+ //frm.getRootPane().revalidate(); // for JDK 1.6 or lower frm.repaint(); } } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if (p1.isShowing()) { frm.remove(p1); frm.add(p2, BorderLayout.CENTER); // Added by me , these three lines frm.revalidate(); // for JDK 1.7+ //frm.getRootPane().revalidate(); // for JDK 1.6 or lower frm.repaint(); } } }); frm.setLayout(new BorderLayout()); frm.add(p1,BorderLayout.CENTER); frm.add(buttonPNL,BorderLayout.SOUTH); frm.setVisible(true); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(300,300); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new PanelTest(); } }); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload