Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- public final class AutoCloseConfirmDialog {
- private AutoCloseConfirmDialog(){
- }
- public static boolean showAutoCloseConfirmDialog(Component parent, String title, String message, int countDown) {
- final JProgressBar progressBar = new JProgressBar(0, countDown);
- Object[] body = {message, progressBar};
- final JOptionPane pane = new JOptionPane(body, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
- final JDialog dialog = pane.createDialog(parent, title);
- progressBar.setPreferredSize(new Dimension(175, 20));
- progressBar.setValue(countDown);
- dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
- final AutoCloseDialogTask task = new AutoCloseDialogTask(progressBar, countDown);
- task.addPropertyChangeListener(evt -> {
- if ("progress".equals(evt.getPropertyName())) {
- if (task.isDone()) {
- pane.setValue(JOptionPane.YES_OPTION);
- dialog.setVisible(false);
- dialog.dispose();
- }
- }
- });
- task.execute();
- dialog.setVisible(true);
- return (int) pane.getValue() == JOptionPane.YES_OPTION;
- }
- private static class AutoCloseDialogTask extends SwingWorker<Void, Void> {
- private JProgressBar progressBar;
- private int limit;
- AutoCloseDialogTask(JProgressBar bar, int countDown) {
- progressBar = bar;
- limit = countDown;
- }
- @Override
- public Void doInBackground() {
- int progress = limit;
- //Initialize progress property.
- setProgress(0);
- while (progress > 0) {
- //Sleep for up to one second.
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ignore) {
- }
- progress--;
- setProgress(progress);
- progressBar.setValue(progress);
- }
- setProgress(100);
- return null;
- }
- @Override
- public void done() {
- }
- }
- }
Add Comment
Please, Sign In to add comment