我想在 JWindow 中显示一条消息一段时间,所以我尝试使用 while() 和 sleep() 函数,但它不起作用。这是应该调用 JWindow (MessageWindow) 的函数。有没有其他方法可以让这个窗口显示2秒?
private void showJWindow() {
boolean flag = true;
final MessageWindow window = new MessageWindow( playerName, playerInAction );
window.setVisible( true );
try {
synchronized( window ) {
while( flag ) {
window.wait( 3000 );
flag = false;
window.setVisible( false );
}
}
} catch( InterruptedException ie ) {
Thread.currentThread().interrupt();
}
}
最佳答案
这是一个使用 Swing 计时器的简短示例。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TestGUI {
public TestGUI() {
final JFrame frame = new JFrame("Test");
JButton press = new JButton("Press Me");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(press);
press.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
final JDialog dialog = new JDialog();
dialog.add(new JLabel("Here for 2 seconds"));
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
Timer timer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestGUI();
}
});
}
}
关于java - 显示 JWindow 一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22894094/