所以我一直在思考一款游戏的想法,一款需要穿越时空的游戏。因此,我编写了一个 JFrame 来显示螺旋的 .gif,但它并没有在对话框显示时结束,而是保留在后台。我可以解决这个问题吗?
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Game {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://s-media-cache-ak0.pinimg.com/originals/e8/e4/02/e8e4028941eb06f2fd5c10f44bfc5e1b.gif");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Trippy");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
//This is the part i want the .gif to end. Instead, it just runs in the background.
JOptionPane.showMessageDialog(null, "You have traveled through space and time!");
}
}
最佳答案
首先,将 defaultCloseOperation
更改为 DO_NOTHING_ON_CLOSE
之类的内容,这至少可以防止用户关闭窗口并阻止 JVM 在您处理时退出自己搭建框架。
接下来,经过短暂的延迟(因为效果真的很酷),您想要在框架上调用 dispose
以关闭它。
为了实现这一点,您可以使用 Swing Timer
,例如...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Game {
public static void main(String[] args) {
new Game();
}
public Game() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
try {
URL url = new URL("https://s-media-cache-ak0.pinimg.com/originals/e8/e4/02/e8e4028941eb06f2fd5c10f44bfc5e1b.gif");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Trippy");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
f.dispose();
//This is the part i want the .gif to end. Instead, it just runs in the background.
JOptionPane.showMessageDialog(null, "You have traveled through space and time!");
}
});
timer.setRepeats(false);
timer.start();
} catch (MalformedURLException exp) {
exp.printStackTrace();
}
}
});
}
}
看看How to use Swing Timers了解更多详情。
您还应该考虑使用 CardLayout
减少实际拥有的窗口数量,这将带来更好的用户体验。
关于Java,结束 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216109/