更新面板

时间:2010-03-04 17:05:08

标签: java panel

我的框架上有一个面板。点击一个按钮我要删除旧面板并制作另一个面板并将该面板添加到我的框架中。(我也使用netbeans) 你能帮帮我,我怎么能这样做?谢谢

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这样:

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