Note that there are some explanatory texts on larger screens.

plurals
  1. POOne JFrame and Two JPanels
    primarykey
    data
    text
    <p>I'm a newbie in Java and I have a problem regarding panels. I have one <code>JFrame</code> and two <code>JPanels</code> in my program. </p> <ul> <li>When I click <code>button1</code>, <code>panel1</code> will show in the frame. </li> <li>When I click <code>button2</code>, <code>panel2</code> will show in the frame and <code>panel1</code> will disappear/hide. </li> </ul> <p>The problem is that <code>panel1</code> can't show only <code>panel2</code>. How to show the two panels in this way?</p> <p>This is my code:</p> <pre><code>public class test{ public static void main(String args[]){ 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); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ p1.setVisible(true); p2.setVisible(false); } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ p1.setVisible(false); p2.setVisible(true); } }); JFrame frm = new JFrame(); frm.setLayout(new BorderLayout()); frm.add(p1,BorderLayout.CENTER); frm.add(p2,BorderLayout.CENTER); frm.add(buttonPNL,BorderLayout.SOUTH); frm.setVisible(true); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(300,300); } } </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.
 

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