我如何才能只退出我从 Main 创建的新 MainGame? Main 有一个原始的游戏层。 MainGame 是一个对话窗口(例如模态窗口)。
Main.java:(主要代码)
public class Main extends JWindow
{
private static JWindow j;
public static MainGame mp;
public static void main(String[] args)
{
new Thread(new Runnable()
{
public void run()
{
mp = new MainGame();
mp.runit();
//mp.stopit();
}
}).start();
j = new Main();
j.setVisible(true);
}
}
MainGame.java:(这是由 Main 扩展的,我只想完成这个)。
public class MainGame extends JWindow
{
private static JWindow j;
public MainGame()
{
// some GUI ...
}
public static void runit()
{
j = new MainGame();
j.setVisible();
}
}
最佳答案
1) 更好的工具是 CardLayout , 就像为新的 Window
创建 Top-Level Container
一样,你只会在 Cards 之间切换
2) 不要在运行时创建大量的Top-Level Container
,因为在当前实例存在之前,JVM 内存中仍然存在,
创建所需数量并重复使用,以避免可能的内存不足
然后你必须调用
setVisible(false)
和setVisible(true)
JWindow
错过了设置setDefaultCloseOperation(Whatever);
的方法
3) 如果你要创建构造函数 public JWindow(Frame owner) , 然后你会直接调用
SwingUtilities.getAccessibleChildrenCount()和 SwingUtilities.getWindowAncestor()
import javax.swing.*;
import java.awt.*;
public class Testing {
private JFrame f = new JFrame("Main Frame");
private JWindow splashScreen = new JWindow();
public Testing() {
splashScreen = new JWindow(f);
splashScreen.getContentPane().setLayout(new GridBagLayout());
JLabel label = new JLabel("Splash Screen");
label.setFont(label.getFont().deriveFont(96f));
splashScreen.getContentPane().add(label, new GridBagConstraints());
splashScreen.pack();
splashScreen.setLocationRelativeTo(null);
splashScreen.setVisible(true);
new Thread(new Runnable() {
@Override
public void run() {
readDatabase();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}).start();
}
public void readDatabase() {
//simulate time to read/load data - 10 seconds?
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
public void createAndShowGUI() {
JLabel label = new JLabel("My Frame");
label.setFont(label.getFont().deriveFont(96f));
f.add(label);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
System.out.println("JFrame getAccessibleChildrenCount count -> "
+ SwingUtilities.getAccessibleChildrenCount(f));
System.out.println("JWindow getParent -> "
+ SwingUtilities.getWindowAncestor(splashScreen));
splashScreen.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Testing t = new Testing();
}
});
}
}
关于java - 如何退出或退出从 Java 中的主 JWindow 创建的从属 JWindow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7518111/