progressbardemo.java

来自「这是一个英文版的《Java程序设计与问题解决》现在好多大学都当成教材」· Java 代码 · 共 89 行

JAVA
89
字号
import java.awt.*;import java.awt.event.*;import javax.swing.*;/*  * ProgressBarDemo.java requires these files: *   LongTask.java *   SwingWorker.java */public class ProgressBarDemo extends JPanel                             implements ActionListener {    public final static int ONE_SECOND = 1000;    private JProgressBar progressBar;    private Timer timer;    private JButton startButton;    private LongTask task;    private JTextArea taskOutput;    private String newline = "\n";    public ProgressBarDemo() {        task = new LongTask();        //Create the demo's UI.        startButton = new JButton("Start");        startButton.setActionCommand("start");        startButton.addActionListener(this);        progressBar = new JProgressBar(0, task.getLengthOfTask());        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);        setLayout(new BorderLayout());        add(panel, BorderLayout.NORTH);        add(new JScrollPane(taskOutput), BorderLayout.CENTER);        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));        //Create a timer.        timer = new Timer(ONE_SECOND, new ActionListener() {            public void actionPerformed(ActionEvent evt) {                progressBar.setValue(task.getCurrent());                String s = task.getMessage();                if (s != null) {                    taskOutput.append(s + newline);                    taskOutput.setCaretPosition(                            taskOutput.getDocument().getLength());                }                if (task.isDone()) {                    Toolkit.getDefaultToolkit().beep();                    timer.stop();                    startButton.setEnabled(true);                    progressBar.setValue(progressBar.getMinimum());                }            }        });    }    /**     * Called when the user presses the start button.     */    public void actionPerformed(ActionEvent evt) {        startButton.setEnabled(false);        task.go();        timer.start();    }    public static void main(String[] args) {        //Make sure we have nice window decorations.        JFrame.setDefaultLookAndFeelDecorated(true);        //Create and set up the window.        JFrame frame = new JFrame("ProgressBarDemo");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frame.setContentPane(new ProgressBarDemo());        //Display the window.        frame.pack();        frame.setVisible(true);    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?