如何删除旧的JPanel并添加新的JPanel? [英] How do I remove an old JPanel and add a new one?

查看:330
本文介绍了如何删除旧的JPanel并添加新的JPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Window(JFrame)中删除旧的JPanel并添加一个新的JPanel。我该怎么办?

I would like to remove an old JPanel from the Window (JFrame) and add a new one. How should I do it?

我尝试了以下内容:

public static void showGUI() {
    JFrame frame = new JFrame("Colored Trails");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    frame.add(partnerSelectionPanel);
    frame.setSize(600,400);
    frame.setVisible(true);
}

private static void updateGUI(final int i, final JLabel label, final JPanel partnerSelectionPanel) {
    SwingUtilities.invokeLater( 
        new Runnable() {
            public void run() {
                label.setText(i + " seconds left.");
            }
            partnerSelectionPanel.setVisible(false); \\ <------------
        }
    );
}

我的代码更新了旧JPanel,然后它使整个JPanel不可见,但它不起作用。编译器抱怨用< ------------ 表示的行。它写道:< identifier>预期,非法开始类型

My code updates the "old" JPanel and then it makes the whole JPanel invisible, but it does not work. The compiler complains about the line indicated with <------------. It writes: <identifier> expected, illegal start of type.

已添加:

我已经成功完成了我需要的操作,并按以下方式完成:

I have managed to do what I needed and I did it in the following way:

public static void showGUI() {
    frame = new JFrame("Colored Trails");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    frame.add(partnerSelectionPanel);
    //frame.add(selectionFinishedPanel);
    frame.setSize(600,400);
    frame.setVisible(true);
}

public static Thread counter = new Thread() {
    public void run() {
        for (int i=4; i>0; i=i-1) {
            updateGUI(i,label);
            try {Thread.sleep(1000);} catch(InterruptedException e) {};
        }
        partnerSelectionPanel.setVisible(false);
        frame.add(selectionFinishedPanel);
    }
};

它有效,但由于以下原因,它看起来不像是一个安全的解决方案:

It works but it does not look to me like a safe solution for the following reasons:


  1. 我从另一个线程更改并向JFrame添加元素。

  2. 我将一个新的JPanel添加到JFrame ,在我已经打包JFrame并使其可见之后。

我应该这样做吗?

推荐答案

setVisible(false),即使在正确的位置,也不会实际从容器中删除面板。如果你想替换面板,请执行以下操作:

setVisible(false), even in the correct place, will not actually remove the panel from the container. If you want to replace the panel do this:

frame.getContentPane().remove(partnerSelectionPanel);
frame.add(new JPanel());
frame.getContentPane().invalidate();
frame.getContentPane().validate();

请注意,frame.getContentPane()。add(Component)与frame.add(Component)相同) - 组件实际上包含在内容窗格中。

Note that frame.getContentPane().add(Component) is the same as frame.add(Component) - the components are actually contained within the content pane.

这篇关于如何删除旧的JPanel并添加新的JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆