为什么 JProgressBar 的 setProgress 方法不接受超过 100 的值?

huangapple go评论80阅读模式
英文:

Why setProgress method for JProgressbar is not accepting value over 100?

问题

我正在设计一个进度条,它接收持续时间 [long] 并开始倒计时,直到达到零。因此,我附加了一个代码片段 [test unite] 来模拟该操作。我向任务对象传递了一个值 = 500 [假设为 int],以在包含程序代码的其余部分之前测试进度条的行为,但不幸的是,除了传递值 = 100 外,它不起作用,我不知道为什么?有人能告诉我在这里漏掉了什么吗?

public class ProgressBarDemo extends JPanel implements ActionListener, PropertyChangeListener {

    // ...(省略部分声明和构造函数)

    class Task extends SwingWorker<Void, Void> {
        int progress;

        public Task(int progress) {
            super();
            this.progress = progress;
        }

        /*
         * 主任务。在后台线程中执行。
         */
        @Override
        public Void doInBackground() {

            // 初始化进度属性。
            setProgress(progress);
            while (progress > 1) {
                // 休眠最多一秒。
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {
                }
                // 使进度减少 10。
                progress -= 10;
                setProgress(progress);
                // 如果您想停止计时器
                if (progress == 20) {
                    progress = 100;
                }
            }
            return null;
        }

        /*
         * 在事件分派线程中执行
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); // 关闭等待光标
            taskOutput.append("完成!\n");
        }
    }

    // ...(省略部分其他方法和GUI创建代码)

    /**
     * 当用户按下“开始”按钮时调用。
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        task = new Task(500);
        task.addPropertyChangeListener(this);
        task.execute();
    }

    /**
     * 当任务的进度属性更改时调用。
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            taskOutput.append(String.format("已完成任务的 %d%%。\n", task.getProgress()));
        }
    }

    // ...(省略部分其他方法和GUI创建代码)

    public static void main(String[] args) {
        // 安排一个作业给事件分派线程:
        // 创建并显示此应用程序的 GUI。
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
英文:

I am designing a progress bar that taking the duration [long] and start a count down until reaches zero. so I attached a snippet code [test unite] to simulate that action. I passed to the task object a value =500 [let's say as int] to test the behavior of the progress bar before including the rest of the program code but unfortunately, it's not working except passing value =100 and I don't know why? can someone tells me what I missed here?

public class ProgressBarDemo extends JPanel implements ActionListener, PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker&lt;Void, Void&gt; {
int progress;
public Task(int progress) {
super();
this.progress = progress;
}
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
// Initialize progress property.
setProgress(progress);
while (progress &gt; 1) {
// Sleep for up to one second.
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
// Make  progress go down by 10.
progress -= 10;
setProgress(progress);
// if you want to stop the timer
if (progress == 20) {
progress = 100;
}
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null); // turn off the wait cursor
taskOutput.append(&quot;Done!\n&quot;);
}
}
public ProgressBarDemo() {
super(new BorderLayout());
// Create the demo&#39;s UI.
startButton = new JButton(&quot;Start&quot;);
startButton.setActionCommand(&quot;start&quot;);
startButton.addActionListener(this);
progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5, 5, 5, 5));
taskOutput.setEditable(false);
JPanel panel = new JPanel();
panel.add(startButton);
panel.add(progressBar);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
* Invoked when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task = new Task(500);
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task&#39;s progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (&quot;progress&quot; == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format(&quot;Completed %d%% of task.\n&quot;, task.getProgress()));
}
}
/**
* Create the GUI and show it. As with all GUI code, this must run on the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame(&quot;ProgressBarDemo&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ProgressBarDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application&#39;s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

}

答案1

得分: 1

你已经使用以下代码行初始化了 JProgressBar:

progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);

因此,你使用了以下构造函数并将最大值设置为 100:

public JProgressBar(int orient, int min, int max)
英文:

You have initialised the JProgressBar with the following line:

progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);

Thus you use the following constructor and set the maximum value to 100:

public JProgressBar(int orient, int min, int max)

huangapple
  • 本文由 发表于 2020年9月26日 21:50:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64078432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定