I am new to java swing, I want to read the text file. while reading that file i want to display the percentage of readed lines in java progress bar. Any sample code is welcome. i tried but i don't know whether my logic is correct or not. How can i acheive this.
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.*;
import javax.swing.border.EtchedBorder;
public class UploadFile
{
JFrame frame;
JProgressBar progressBar_1;
public static void main(String args[])throws IOException
{
UploadFile obj=new UploadFile();
obj.redfile();
}
public UploadFile()
{
frame = new JFrame();
frame.setBounds(100, 100, 400, 200);
frame.getContentPane().setLayout(null);
progressBar_1 = new JProgressBar();
progressBar_1.setBounds(102, 40, 150, 16);
frame.getContentPane().add(progressBar_1);
progressBar_1.setStringPainted(true);
frame.setVisible(true);
}
public void redfile()
{
try{
String s="";
File f1=new File("sample.txt");
FileReader fr=new FileReader(f1);
BufferedReader br=new BufferedReader(fr);
Task t=new Task();
t.start();
while((s=br.readLine())!=null){
try{Thread.sleep(200);}catch(Exception e){
}
System.out.println("-->"+s);
}
}catch(Exception e){
}
}
private class Task extends Thread
{
public void run()
{
for(int j=0;j<=100; j+=5)
{
progressBar_1.setValue(j);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
}
You don't need any Thread to update the progress bar status. You know the total no of bytes present in the file. Just calculate the percent done on the basis of bytes read.
public void redfile() {
try {
...
long totalLength = f1.length();
double lengthPerPercent = 100.0 / totalLength;
long readLength = 0;
System.out.println(totalLength);
while ((s = br.readLine()) != null) {
readLength += s.length();
progressBar_1.setValue((int) Math.round(lengthPerPercent * readLength));
...
}
progressBar_1.setValue(100);
fr.close();
} catch (Exception e) {
...
}
}