欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GUI之进度条JProgressBar 的使用

程序员文章站 2022-03-26 14:40:55
...

package com.example;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

/**
* Created by jiawei on 2018/8/4.
*/

public class JProgressBarDemo extends JFrame{
MyPanel panel = new MyPanel();

public JProgressBarDemo() throws HeadlessException {

    panel.setLayout(new FlowLayout(1,5,15));
    JButton start = new JButton("start");
    start.setForeground(Color.RED);
    JProgressBar bar = new JProgressBar();
    bar.setOrientation(JProgressBar.HORIZONTAL);
    bar.setPreferredSize(new Dimension(300,20));
    bar.setMinimum(0);
    bar.setMaximum(100);
    bar.setValue(0);
    bar.setStringPainted(true);
    bar.setBackground(Color.blue);
    bar.setBorderPainted(true);
    panel.add(start);
    panel.add(bar);
    add(panel,BorderLayout.CENTER);
    pack();

    start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                       for(int i=0; i<=100;i++){
                           bar.setValue(i);
                           try {
                               Thread.sleep(100);
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                       }
                       bar.setString("下载完成!");
                }
            }).start();
        }
    });
}

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JProgressBarDemo demo = new JProgressBarDemo();
            demo.setTitle("myProgressBar");
            demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            demo.setLocationByPlatform(true);
            demo.setSize(new Dimension(400,100));
            //让窗体居中显示
            demo.setLocationRelativeTo(null);
            demo.setVisible(true);
        }
    });
}

}

class MyPanel extends JPanel{

@Override
public void setPreferredSize(Dimension dimension) {
    super.setPreferredSize(new Dimension(400,400));
}

}

相关标签: GUI