updating a panel

半腔热情 提交于 2019-11-28 13:59:51

问题


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 you please help me that how can i do that?thanks


回答1:


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);



回答2:


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();


来源:https://stackoverflow.com/questions/2381169/updating-a-panel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!