gpt4 book ai didi

java - 自动关闭对话框

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:14 25 4
gpt4 key购买 nike

我对 JOptionPane 有疑问,如何自动关闭对话框,我可以使用该对话框在事件中提醒用户并在延迟后自动关闭,而无需关闭对话框?

public class ShutdownComputer
{
public static void main(String[]args)
{
int wholeTimeBeforeShutdown=0;

int hour=0;
int minute=0;
int second=0;

try
{
String a=JOptionPane.showInputDialog(null,"HOUR","HOUR BEFORE SHUTDOWN",JOptionPane.QUESTION_MESSAGE);
String b=JOptionPane.showInputDialog(null,"MINUTE","MINUTE BEFORE SHUTDOWN",JOptionPane.QUESTION_MESSAGE);
String c=JOptionPane.showInputDialog(null,"SECOND","SECOND BEFORE SHUTDOWN",JOptionPane.QUESTION_MESSAGE);

if((a==null)||(a.equals("")))
{
a="0";
}

if((b==null)||(b.equals("")))
{
b="0";
}

if((c==null)||(c.equals("")))
{
c="0";
}

int e=Integer.parseInt(a);
int f=Integer.parseInt(b);
int g=Integer.parseInt(c);

wholeTimeBeforeShutdown=wholeTimeBeforeShutdown+((e*60)*60);
wholeTimeBeforeShutdown=wholeTimeBeforeShutdown+(f*60);
wholeTimeBeforeShutdown=wholeTimeBeforeShutdown+(g);

wholeTimeBeforeShutdown=wholeTimeBeforeShutdown*1000;


Thread.sleep(wholeTimeBeforeShutdown);

JOptionPane.showMessageDialog(null, "You only have less than 2 minutes left");

Runtime.getRuntime().exec("shutdown -r -f -t 120");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}

最佳答案

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;

    final String msg="Shutdown\nWill happen automatically in "; 
final JOptionPane op=new JOptionPane(null, JOptionPane.INFORMATION_MESSAGE);
final JDialog d=op.createDialog("Shutdown");
d.setModal(true);
// deadline in three hours:
final long deadline=System.nanoTime()+TimeUnit.HOURS.toNanos(3);
ActionListener updater=new ActionListener() {
public void actionPerformed(ActionEvent e)
{
long left=deadline-System.nanoTime();
if(left<=0) {
d.dispose();
return;
}
String time;
long t=TimeUnit.NANOSECONDS.toHours(left);
if(t>0) time=t>1? t+" hours": "one hour";
else {
t=TimeUnit.NANOSECONDS.toMinutes(left);
time=t>1? t+" minutes": "one minute";
}
op.setMessage(msg+time);
}
};
updater.actionPerformed(null);//update initial message
d.pack(); // resize dialog for the updated message
final Timer t=new Timer(1000, updater);
t.setInitialDelay(0);
t.setRepeats(true);
t.start();
d.setVisible(true);
t.stop();
// do your action

请注意,此代码发出的消息将向下舍入时间值,但我认为这对您来说是一个可用的起点。

关于java - 自动关闭对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18493341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com