updating a panel

后端 未结 2 1908
生来不讨喜
生来不讨喜 2020-12-22 13:41

I have a panel on my frame .and by clicking on a button I want to delete the old panel and make the other panel and add that panel to my frame.(also I use netbeans) would yo

相关标签:
2条回答
  • 2020-12-22 13:50
    JFrame frame = new JFrame();
    final JPanel origPanel = new JPanel();
    frame.add(origPanel, BorderLayout.CENTER);
    
    MouseListener ml = new MouseAdapter() {
      public void mouseClicked(MouseEvent evt) {
        // Mouse clicked on panel so remove existing panel and add a new one.
        frame.remove(origPanel);
        frame.add(createNewPanel(), BorderLayout.CENTER);
    
        // Revalidate frame to cause it to layout the new panel correctly.
        frame.revalidate();
    
        // Stop listening to origPanel (prevent dangling reference).
        origPanel.removeMouseListener(this);
      }
    }
    
    origPanel.addMouseListener(ml);
    
    0 讨论(0)
  • 2020-12-22 14:08

    This way:

        final JFrame frame = new JFrame();
        frame.setSize(200, 200);
    
        final JPanel panelA = new JPanel();
        final JPanel panelB = new JPanel();
        JButton button = new JButton("Switch");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.remove(panelA);
                frame.add(panelB);
                frame.show();
            }
        });
        JLabel label = new JLabel("This is panel B. Panel A is gone!");
        panelB.add(label);
        panelA.add(button);
        frame.add(panelB);
        frame.add(panelA);
        frame.show();
    
    0 讨论(0)
提交回复
热议问题