📜  Java Swing-JProgressBar

📅  最后修改于: 2020-09-30 06:07:13             🧑  作者: Mango

Java JProgressBar

JProgressBar类用于显示任务的进度。它继承了JComponent类。

JProgressBar类声明

我们来看一下javax.swing.JProgressBar类的声明。

public class JProgressBar extends JComponent implements SwingConstants, Accessible

常用的构造函数:

Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string text.
JProgressBar(int min, int max) It is used to create a horizontal progress bar with the specified minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar with the specified orientation, it can be either Vertical or Horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, int min, int max) It is used to create a progress bar with the specified orientation, minimum and maximum value.

常用方法:

Method Description
void setStringPainted(boolean b) It is used to determine whether string should be displayed.
void setString(String s) It is used to set value to the progress string.
void setOrientation(int orientation) It is used to set the orientation, it may be either vertical or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress bar.

Java JProgressBar示例

import javax.swing.*;  
public class ProgressBarExample extends JFrame{  
JProgressBar jb;  
int i=0,num=0;   
ProgressBarExample(){  
jb=new JProgressBar(0,2000);  
jb.setBounds(40,40,160,30);       
jb.setValue(0);  
jb.setStringPainted(true);  
add(jb);  
setSize(250,150);  
setLayout(null);  
}  
public void iterate(){  
while(i<=2000){  
  jb.setValue(i);  
  i=i+20;  
  try{Thread.sleep(150);}catch(Exception e){}  
}  
}  
public static void main(String[] args) {  
    ProgressBarExample m=new ProgressBarExample();  
    m.setVisible(true);  
    m.iterate();  
}  
}  

输出: