Java,结束JFrame

时间:2015-08-26 00:17:15

标签: java swing

所以我一直在想一个游戏的想法,一个人需要一直旅行。所以我写了一个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!");
}

}

1 个答案:

答案 0 :(得分:2)

首先,将DO_NOTHING_ON_CLOSE更改为类似dispose的内容,这至少会阻止用户关闭窗口并在您自行处理框架时停止退出JVM。

接下来,经过短暂的延迟(因为效果真的很酷),你想在框架上调用Timer以便关闭它。

为了实现这一目标,您可以使用Swing 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(); } } }); } } ,例如......

ContainerFragment

有关详细信息,请查看How to use Swing Timers

您还应该考虑使用CardLayout来减少实际拥有的窗口数量,这样可以提供更好的用户体验。