jprogressbar visible and working on button click
public NewJDialog(java.awt.Frame 开发者_开发技巧parent, boolean modal) {
super(parent, modal);
initComponents();
jProgressBar1.setVisible(false);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton1.setEnabled(false);
jProgressBar1.setVisible(true);
repaint();
for(int i=0;i<=100;i+=5){
jProgressBar1.setValue(i);
// jProgressBar1.setIndeterminate(false);
try{
jProgressBar1.paintImmediately(0, 0, 100, 100);//0, 1, 100, 10
Thread.sleep(100);
jProgressBar1.setStringPainted(true);
}catch(Exception e){}
}
I use above code for using a Jprogressbar in a JDialog. If I use this I can see a progressbar after completing its process(100 %) and also I don't want to show the progressbar upto buttonclick.
- Use a separate Thread for running your task. The progress bar doesn't have a chance to get painted on the GUI thread. You need something like SwingWorker to help you out.
- Add the progress bar to the GUI after the button click.
- Refer to the Java tutorial for a walk through on how to set it up.
//Simplest way of using JProgressBar
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
class logindemo extends JFrame implements ActionListener
{
JProgressBar pb;
JButton b1;
logindemo()
{
super("LOGIN FORM");
setLayout(null);
b1=new JButton("LOGIN");
b1.setBackground(Color.yellow);
pb=new JProgressBar(1,100);
pb.setValue(0);
pb.setStringPainted(true);
pb.setForeground(Color.red);
pb.setBackground(Color.white);
b1.setBounds(20,20,80,25);pb.setBounds(110,20,200,25);
pb.setVisible(false);
add(b1);
add(pb);
b1.addActionListener(this);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
int i=0;
if(e.getSource()==b1)
{
pb.setVisible(true);
try
{
while(i<=100)
{
Thread.sleep(50);
pb.paintImmediately(0, 0, 200, 25);
pb.setValue(i);
i++;
}
}
catch(Exception e1)
{
System.out.print("Caughted exception is ="+e1);
}
}
}
public static void main(String arg[])
{
logindemo m=new logindemo();
m.setSize(330,100);
m.setVisible(true);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - m.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - m.getHeight()) / 2);
m.setLocation(x, y);
}
}
/*
By
Dr. Amit Kumar Kapoor
Assistant Professor, Maharaja Agrasen Institute of Management & Technology, Jagadhri
E-mail ID: - akbrightfuture@gmail.com
*/
精彩评论