分享一款可公用的Swing进度条
Swingadmin 发布于:2018-08-31 21:53:54
阅读:loading
二回在使用swing开发软件时,可以使用得到,但需进一步进行更好的封装吧。目前实现主要为实现的功能项有:
(1)、公用组件,无需在调用窗口增加控件(新弹出无状态属性窗口,居父窗口中间位置,有需要可增加鼠标点击时的位置);
(2)、显示进度时主窗口进入不能被cao作状态;
(3)、线程异步显示真实进度信息(由代码设置进度数据);
(加水印把这个gif图片给加的反而看不清楚了)
调用类实例
package cn.chendd.examples;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
super.setTitle("HELLO");
final ProgressFrame progressFrame = new ProgressFrame(this);
JButton testButton = new JButton("测试");
testButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
progressFrame.showProgress();//显示
new Thread(new Runnable(){
@Override
public void run() {
for(int i=1 ; i <= 100 ; i++){
progressFrame.setProressBarValue(i);
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressFrame.endProgressBar();
}
}).start();
}
});
testButton.setBounds(20, 20, 60, 25);
super.add(testButton , BorderLayout.CENTER);
super.setLayout(new BorderLayout());
super.setSize(400, 200);
super.setLocationRelativeTo(this);
super.setVisible(true);
super.setAlwaysOnTop(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Main();
}
}
进度条组件类
package cn.chendd.examples;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class ProgressFrame extends JDialog {
private static final long serialVersionUID = 1L;
protected Main main;
final JProgressBar progressBar = new JProgressBar();
public ProgressFrame(Main main){
this.main = main;
super.setSize(300, 24);
super.setLayout(new BorderLayout());
//super.setModal(true);
progressBar.setForeground(new Color(10,36,106));
progressBar.setBackground(new Color(212,208,200));
progressBar.setStringPainted(true);//显示进度文本
super.add(progressBar , BorderLayout.CENTER);
super.setLocationRelativeTo(main);
super.setUndecorated(true);
super.setAlwaysOnTop(true);
super.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
public void showProgress() {
Point point = main.getLocation();
Dimension mainSize = main.getSize();
int mainWidth = (int) mainSize.getWidth();
int mainHeight = (int) mainSize.getHeight();
int locationX = (int) point.getX();
int locationY = (int) point.getY();
int x = locationX + (mainWidth - super.getWidth()) / 2;
int y = locationY + (mainHeight - super.getHeight()) / 2;
super.setLocation(x, y);
super.setVisible(true);
main.setEnabled(false);
}
public void setProressBarValue(int value){
this.progressBar.setValue(value);
}
/**
* <pre>
* 进度条结束,关闭进度窗口
* </pre>
*/
public void endProgressBar(){
this.setProressBarValue(0);
this.setVisible(false);
main.setEnabled(true);
}
}
点赞