Xin chào, tôi muốn hiển thị JOptionPane.showMessageDialog(null, "Appication already running");
Java: Hiển thị hộp thoại tin nhắn trong 10 giây và xóa?
trong 10 giây và sau đó xóa nó. Làm sao tôi có thể?
Xin chào, tôi muốn hiển thị JOptionPane.showMessageDialog(null, "Appication already running");
Java: Hiển thị hộp thoại tin nhắn trong 10 giây và xóa?
trong 10 giây và sau đó xóa nó. Làm sao tôi có thể?
Bạn có thể tạo một JOptionPane theo cách thủ công, không có phương pháp tĩnh:
JOptionPane pane = new JOptionPane("Your message", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(parent, "Title");
thì bạn có thể hiển thị hộp thoại và kích hoạt bộ hẹn giờ để ẩn nó sau mười giây.
làm khung nhỏ như JOptionPane, hiển thị nó trong chủ đề và định đoạt sau 10 giây
My Java là một chút gỉ nhưng bạn sẽ có thể chỉ cần sử dụng các tiêu chuẩn Timer
lớp:
import java.util.Timer;
int timeout_ms = 10000;//10 * 1000
Timer timer = new Timer();
timer.schedule(new CloseDialogTask(), timeout_ms);
//implement your CloseDialogTask:
class CloseDialogTask extends TimerTask {
public void run() {
//close dialog code goes here
}
}
Tôi đã thử các câu trả lời này và gặp sự cố khi hiển thị hộp thoại là cuộc gọi chặn, vì vậy bộ hẹn giờ không thể hoạt động. Sau đây là xung quanh vấn đề này.
JOptionPane opt = new JOptionPane("Application already running", JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{}); // no buttons
final JDialog dlg = opt.createDialog("Error");
new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(10000);
dlg.dispose();
}
catch (Throwable th)
{
tracea("setValidComboIndex(): error :\n"
+ cThrowable.getStackTrace(th));
}
}
}).start();
dlg.setVisible(true);
// =====================
// yes = 0, no = 1, cancel = 2
// timer = uninitializedValue, [x] = null
public static void DialogBox() {
JOptionPane MsgBox = new JOptionPane("Continue?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
JDialog dlg = MsgBox.createDialog("Select Yes or No");
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.addComponentListener(new ComponentAdapter() {
@Override
// =====================
public void componentShown(ComponentEvent e) {
// =====================
super.componentShown(e);
Timer t; t = new Timer(7000, new ActionListener() {
@Override
// =====================
public void actionPerformed(ActionEvent e) {
// =====================
dlg.setVisible(false);
}
});
t.setRepeats(false);
t.start();
}
});
dlg.setVisible(true);
Object n = MsgBox.getValue();
System.out.println(n);
System.out.println("Finished");
dlg.dispose();
}
}
Điều này có thể giải quyết được vấn đề, nhưng bạn nên giải thích cách thức và lý do giải quyết nó, không chỉ là mã. – Adam
với xích đu, nó là thích hợp hơn để sử dụng javax.swing.Timer thay thế này. –