How to omit the “Cancel” button in Java ProgressMonitor?

后端 未结 2 1690
清酒与你
清酒与你 2020-12-17 06:10

My task is necessary and shouldn\'t be canceled, how do I ask ProgressMonitor not to display the \"Cancel\" button, so when it finishes, it will auto close the panel.

<
相关标签:
2条回答
  • 2020-12-17 07:02

    That's not possible. You can however create a custom progress monitor as outlined in this tutorial.

    0 讨论(0)
  • 2020-12-17 07:07

    I was thinking maybe I can ask it to return the components in it and delete the button

    Using the ProgressMonitorDemo from the Swing tutorial (linked to by BalusC) I made the following changes:

    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName() ) {
            int progress = (Integer) evt.getNewValue();
            progressMonitor.setProgress(progress);
    
            //  Added this
    
            AccessibleContext ac = progressMonitor.getAccessibleContext();
            JDialog dialog = (JDialog)ac.getAccessibleParent();
            java.util.List<JButton> components =
                SwingUtils.getDescendantsOfType(JButton.class, dialog, true);
            JButton button = components.get(0);
            button.setVisible(false);
    
            // end of change
    
            String message =
                String.format("Completed %d%%.\n", progress);
            progressMonitor.setNote(message);
            taskOutput.append(message);
            if (progressMonitor.isCanceled() || task.isDone()) {
                Toolkit.getDefaultToolkit().beep();
                if (progressMonitor.isCanceled()) {
                    task.cancel(true);
                    taskOutput.append("Task canceled.\n");
                } else {
                    taskOutput.append("Task completed.\n");
                }
                startButton.setEnabled(true);
            }
        }
    }
    

    You will need to download the Swing Utils class as well.

    The code should only be executed once, otherwise you get a NPE when the dialog closes. I'll let you tidy that up :).

    0 讨论(0)
提交回复
热议问题