新来的 - 我的第一个问题。不管怎样,我在这里是因为我想制作一个JFrame,我想它的计时时间为10000毫秒,然后当它关闭时,它应该打开另一个(在另一个类中)。我已经完成了计时器部分,而不是“关闭定时 JFrame,并打开另一个”部分。
我记得这样做过,并找到了答案。它类似于 NewClass.show()
(“NewClass”是应该打开的类名称),然后输入 OldClass.dispose()
(“OldClass”是应该关闭的类名称)。
这是迄今为止我的代码:
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SplashScreen extends JPanel {
public SplashScreen() {
setOpaque(false);
setLayout(new FlowLayout());
}
public static void main(String[] args) {
final JFrame frame = new JFrame("Loading game...");
frame.setSize(800, 600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplashScreen background = new SplashScreen();
frame.add(background);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
//I want to place my code here so then this class will close, and then the other class will open
}
});
timer.setRepeats(false);
timer.start();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("Waiting.png");
Point hotSpot = new Point(0,0);
Cursor cursor = toolkit.createCustomCursor(image, hotSpot, "Cursor");
frame.setCursor(cursor);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width - w) / 2;
int y = (dim.height - h) / 2;
frame.setLocation(x, y);
JButton button = new JButton();
JPanel panel = new JPanel();
}
public void paint(Graphics g) {
Image a=Toolkit.getDefaultToolkit().getImage("Splash Screen.gif");
g.drawImage(a,0,0,getSize().width,getSize().height,this);
super.paint(g);
}
}
我没有创建第二个类(它将被称为“LoadingScreen.class”,但我会,它只会有“JSomethings”或其他任何内容(如 JFrame、JPanel 等...)
我可以制作第二个类(class),但我想要的只是第一个类(class)在计时器完成 10 秒或 10000 毫秒后关闭,然后自动打开第二个类(class)。
谢谢
最佳答案
尝试将调用添加到您的第二个类,如下所示
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
frame.dispose();
//I want to place my code here so then this class will close, and then the other class will open
//SplashScreen screen = new SplashScreen();
//screen.showGUI();
}
});
另一个好的做法是最后调用frame.setVisible(true)
,这样您就不会发现屏幕上的帧位置有任何漂移。
关于java - 如何使 JFrame(带计时器)从另一个类打开另一个 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131333/