繁体   English   中英

如何关闭您拥有的框架并在 JAVA 中打开一个新框架

[英]How to close a frame that you have and open a new frame in JAVA

我想打开一个新框架来显示更多细节,并让我在一个新窗口上开始,就像一个新的新页面

这是我的代码:

public class OBA {

    public static void main(String[] args) {

        JFrame f = new JFrame("OBA");
        f.setSize(1366, 768);
        f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        f.setLayout(null);
        f.setVisible(true);

        JLabel l1 = null;
        JLabel l2 = null;
        JLabel l3 = null;
        l1 = new JLabel("Welcome");
        l1.setBounds(625, 100, 100, 100);
        l1.setFont(new Font("Courier New", Font.BOLD, 22));
        l1.setForeground(Color.BLACK);
        l2 = new JLabel("To", JLabel.CENTER);
        l2.setBounds(625, 100, 100, 150);
        l2.setFont(new Font("Courier New", Font.BOLD, 22));
        l2.setForeground(Color.BLACK);
        l3 = new JLabel("OBA", JLabel.CENTER);
        l3.setBounds(623, 100, 100, 200);
        l3.setFont(new Font("Courier New", Font.BOLD, 22));
        l3.setForeground(Color.BLACK);
        f.add(l1);
        f.add(l2);
        f.add(l3);
    }
}

您创建了 JFrame, f ,因此您知道如何创建 JFrame。 f.dispose()关闭该框架,您可以调用f.dispose() 如果您只想隐藏它,请调用f.setVisible(false) 要打开一个新框架,请执行类似于创建f

我不知道你为什么要这样做,但如果(正如我解释你的问题)你想关闭当前窗口并立即创建一个新窗口,在很多情况下有一种更简单的方法。 代替处置一个 JFrame 并创建另一个 JFrame,您可以保留现有的 JFrame 并删除其中已经存在的任何内容,例如连续调用f.remove() ,每个要删除的组件都调用一次。 如果您将组件放在LayoutManager而不是直接放入框架中,则可以使用f.setLayout()将另一个LayoutManager放入并f.setLayout()交换所有内容,这可能会更容易。

有关 JFrame 的更多信息,请参阅 Oracle 文档

编辑(回应评论):如果您想在更改显示内容之前等待,则需要使用导致延迟的方法。 java.lang.thread有一个静态方法sleep()就是这样做的; 要等待五秒钟,您可以使用Thread.sleep(5000); (因为它接受毫秒)。 但是,如果您中断正在运行sleep()的线程,则此方法可能会引发异常。 所以你应该把它包装在一个 try 块中:

try {
    Thread.sleep(5000);
} catch(InterruptedException ex) {
    // Your thread was interrupted (maybe the user quit the program?)
    // Handle that here.
}
f.remove(/* The element to remove goes here. */);
// Etc...

当然,由于这会使线程暂停五秒钟,因此您不应在处理用户输入等事情的线程中调用sleep() ,这可能会在这五秒钟内发生。

Oracle 也有这方面的文档

这将成为与原始问题不同的主题,但是 Java 中的线程(以及一般情况下)有很多使人们感到困惑的小错综复杂。 如果您需要更多有关sleep()或线程的帮助,您可能想提出一个新问题,或者寻找与您的问题相关的现有问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM