timer action performs only after the thread is finished - java

I have a swing GUI named SpyBiteDemo, it will call another class(Parser) and do some calculations and show some data in a jtable inside this GUI(SpyBiteDemo). I have a jbutton1 and I want to when click on it to show my timer to begin like 1,2,3,4,5,....seconds
what happens is my timer is running correctly however it does not show value unless it is done with all the program that is filling the jtable which means the action it is detecting is I perform the action after jtable appears.
I am a complete newbie on Java for event listeners and I have searched timer, timer task, schedule, everything and could not understand what's wrong.I also tried while(true) and did not fix it.I also tried duration of 1000,0,everything no affects.
I tried to use action command,sleeping the thread, it did not help.here is what I did:
public class SpyBiteDemo extends javax.swing.JFrame {
/**
* Creates new form SpyBiteDemo
*/
private long startTime;
Timer timer = new Timer(0, new TimerListener());
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent aEvt) {
long time = (System.currentTimeMillis() - startTime) / 1000;
label3.setText(time + " seconds");
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
startTime = evt.getWhen();
String SeedUrl = jTextField1.getText();
Parser P = new Parser(this);
jTable2.setVisible(true);
}
}
it will start showing label3 value only after it is filling the jtable on my jframe.I want the timer to start from when I am clicking the button.
with trashgod's links I had come up with this example which is comepletely runnable on your machine, this works perfect except that when I the program finishes, it does not stop the timer since I don't know where to do it, I know I should do it in addPropertyChangeListener, however I do not have timer value.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication7;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
* #see http://stackoverflow.com/a/25526869/230513
*/
public class DisplayLog {
private static final String NAME = "C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\scosche.sql";
private static class LogWorker extends SwingWorker<TableModel, String> {
private final File file;
private final DefaultTableModel model;
private LogWorker(File file, DefaultTableModel model) {
this.file = file;
this.model = model;
model.setColumnIdentifiers(new Object[]{file.getAbsolutePath()});
}
#Override
protected TableModel doInBackground() throws Exception {
BufferedReader br = new BufferedReader(new FileReader(file));
String s;
while ((s = br.readLine()) != null) {
publish(s);
}
return model;
}
#Override
protected void process(List<String> chunks) {
for (String s : chunks) {
model.addRow(new Object[]{s});
}
}
#Override
protected void done() {}
}
private void display() {
JFrame f = new JFrame("DisplayLog");
JLabel m=new JLabel("time");
JButton jb=new JButton("run");
f.add(jb,BorderLayout.BEFORE_FIRST_LINE);
f.add(m, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JProgressBar jpb = new JProgressBar();
f.add(jpb, BorderLayout.NORTH);
f.add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LogWorker lw = new LogWorker(new File(NAME), model);
lw.addPropertyChangeListener((PropertyChangeEvent ev) -> {
SwingWorker.StateValue s = (SwingWorker.StateValue) ev.getNewValue();
jpb.setIndeterminate(s.equals(SwingWorker.StateValue.STARTED));
});
lw.execute();
int timeDelay = 0;
ActionListener time;
time = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
m.setText(System.currentTimeMillis() / 1000 + "seconds");
}
};
Timer timer=new Timer(timeDelay, time);
timer.start();
if(lw.isDone())
timer.stop();
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new DisplayLog().display();
});
}
}

It looks like the rows that comprise your table come from the network with variable, indeterminate latency. As shown here, you can load data into your TableModel in the background of a SwingWorker. As shown here, you can calculate intermediate progress in a way that makes sense for your application and display it in a PropertyChangeListener.

Related

How to run method with JProgressBar

I have a function called CreateAccount. I need it to run and also need to show a progress bar. When I click the button, the method will start. And I need to start showing loading progress bar. Once method is done progress bar also should stop at 100. If the method gets more time to do the job, progress bar also needs to load slowly.
I tried using following code but it is not synchronizing progress bar with the method. So how can I do that?
Here is my code:
private static int t = 0;
private void createAccountBtnActionPerformed(java.awt.event.ActionEvent evt) {
progressBar.setValue(0);
progressBar.setStringPainted(true);
new Thread(new Runnable() {
#Override
public void run() {
//CreateAccount();
for (t = 0; t <= 100; t++) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CreateAccount();
progressBar.setValue(t);
}
});
try {
java.lang.Thread.sleep(100);
}
catch(InterruptedException e) { }
}
}
}).start();
}
Because of the single threaded nature of Swing, you can't perform long running or blocking operations from within the context of the Event Dispatching Thread, nor can you update the UI from outside the context of the Event Dispatching Thread.
See Concurrency in Swing for more details.
Both these things you are taking care of. The problem is, this means that it's possible for the background thread to do more work than is been presented on the UI and there's nothing you can do about. The the best bet is simply trying too keep the UI up-to-date as much as possible
A possible better solution might be to use a SwingWorker, which is designed to make updating the UI easier. See Worker Threads and SwingWorker for more details.
The following example shows a progress bar which will run for 10 seconds with a random delay of up to 500 milliseconds between each update. The progress bar is then update based on the amount of time remaining.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public final class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar pb;
private JButton btn;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
btn = new JButton("Go");
pb = new JProgressBar();
add(btn, gbc);
add(pb, gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
makeItProgress();
}
});
}
protected void makeItProgress() {
SwingWorker<Double, Double> worker = new SwingWorker<Double, Double>() {
#Override
protected Double doInBackground() throws Exception {
Duration duration = Duration.ofSeconds(10);
Instant startTime = Instant.now();
Duration runningTime = Duration.ZERO;
Random rnd = new Random();
setProgress(0);
do {
Thread.sleep(rnd.nextInt(500));
Instant now = Instant.now();
runningTime = Duration.between(startTime, now);
double progress = (double) runningTime.toMillis() / (double) duration.toMillis();
setProgress((int) (progress * 100));
} while (duration.compareTo(runningTime) >= 0);
setProgress(100);
return 1.0;
}
};
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
SwingWorker worker = (SwingWorker) evt.getSource();
if (evt.getPropertyName().equals("progress")) {
int value = (int) evt.getNewValue();
pb.setValue(value);
} else if (evt.getPropertyName().equals("state") && worker.getState() == SwingWorker.StateValue.DONE) {
pb.setValue(100);
btn.setEnabled(true);
}
}
});
worker.execute();
}
}
}
The point of this example is, the progress and the work are mixed into a single operation (the doInBackground method of the SwingWorker) so they are more closely related. The SwingWoker then notifies the PropertyChangeListener of updates, to which it can react to safely on the Event Dispatching Thread

How to terminate Java program without closing a window

I have created a Java application that goes through hundreds of documents after user clicks "Run" button. Is there a way to terminate the program and leave the GUI running? All I want to be able to stop is the process of reading the documents.
System.exit(0) is not the solution I am looking for as my whole app closes.
It's difficult to say something without to see your application. But probably this piece of code will help you to understand how to implement what you want:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
public class SwingWorkerTest implements Runnable {
private JButton cancelButton = new JButton("Cancel");
private JButton runButton = new JButton("Run");
private JLabel label = new JLabel("Press 'Run' to start");
private LongWorker longWorker;
#Override
public void run() {
JFrame frm = new JFrame("Long task test");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker.terminate();
}
});
runButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker = new LongWorker();
runButton.setEnabled(false);
cancelButton.setEnabled(true);
label.setText("Task in progress. Press 'Cancel' to terminate.");
longWorker.execute();
}
});
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
bottomPanel.add(runButton);
bottomPanel.add(cancelButton);
frm.add(label);
frm.add(bottomPanel, BorderLayout.SOUTH);
frm.setSize(400, 200);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new SwingWorkerTest());
}
private class LongWorker extends SwingWorker<Void, Void> {
private volatile boolean terminated;
#Override
protected Void doInBackground() throws Exception {
// check special variable tov determine whether this task still active
for (int i = 0; i < 1000 && !terminated; i++) {
readFile();
}
return null;
}
#Override
protected void done() {
if (terminated) {
label.setText("Process terminated. Press 'Run' to restart.");
} else {
label.setText("Process done. Press 'Run' to restart.");
}
cancelButton.setEnabled(false);
runButton.setEnabled(true);
}
// dummy method - make 10 milliseconds sleep
private void readFile() {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
// Nothing here
}
}
public void terminate() {
terminated = true;
}
}
}

Java SwingWorker with JDialog showing JProgressBar during JDBC network operation

I have a frame which has a button, when it is pressed a JDialog with a progress bar is shown and some data is being fetched using jdbc driver (progress bar is being updated). I needed a cancel button, so I spent some time figuring out how to connect everything. It seems to be working, but I sincerely am not sure if this way is any good. If someone has some spare time please check this code and tell me if anything is wrong with it - mainly with the whole SwingWorker and cancellation stuff.
On my pc (linux) the unsuccessful network connection attempt (someNetworkDataFetching method) takes a whole minute to timeout, do I have to worry about the SwingWorkers which are still working (waiting to connect despite being cancelled) when I try to create new ones?
Note: you need mysql jdbc driver library to run this code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Test extends JFrame {
private JProgressBar progressBar = new JProgressBar();
private JLabel label = new JLabel();
private DataFetcherProgress dfp;
/**
* This class holds retrieved data.
*/
class ImportantData {
ArrayList<String> chunks = new ArrayList<>();
void addChunk(String chunk) {
// Add this data
chunks.add(chunk);
}
}
/**
* This is the JDialog which shows data retrieval progress.
*/
class DataFetcherProgress extends JDialog {
JButton cancelButton = new JButton("Cancel");
DataFetcher df;
/**
* Sets up data fetcher dialog.
*/
public DataFetcherProgress(Test owner) {
super(owner, true);
getContentPane().add(progressBar, BorderLayout.CENTER);
// This button cancels the data fetching worker.
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
df.cancel(true);
}
});
getContentPane().add(cancelButton, BorderLayout.EAST);
setLocationRelativeTo(owner);
setSize(200, 50);
df = new DataFetcher(this);
}
/**
* This executes data fetching worker.
*/
public void fetchData() {
df.execute();
}
}
class DataFetcher extends SwingWorker<ImportantData, Integer> {
DataFetcherProgress progressDialog;
public DataFetcher(DataFetcherProgress progressDialog) {
this.progressDialog = progressDialog;
}
/**
* Update the progress bar.
*/
#Override
protected void process(List<Integer> chunks) {
if (chunks.size() > 0) {
int step = chunks.get(chunks.size() - 1);
progressBar.setValue(step);
}
}
/**
* Called when worker finishes (or is cancelled).
*/
#Override
protected void done() {
System.out.println("done()");
ImportantData data = null;
try {
data = get();
} catch (InterruptedException | ExecutionException | CancellationException ex) {
System.err.println("done() exception: " + ex);
}
label.setText(data != null ? "Retrieved data!" : "Did not retrieve data.");
progressDialog.setVisible(false);
}
/**
* This pretends to do some data fetching.
*/
private String someNetworkDataFetching() throws SQLException {
DriverManager.getConnection("jdbc:mysql://1.1.1.1/db", "user", "pass");
// Retrieve data...
return "data chunk";
}
/**
* This tries to create ImportantData object.
*/
#Override
protected ImportantData doInBackground() throws Exception {
// Show the progress bar dialog.
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dfp.setVisible(true);
}
});
ImportantData data = new ImportantData();
try {
int i = 0;
// There is a network operation here (JDBC data retrieval)
String chunk1 = someNetworkDataFetching();
if (isCancelled()) {
System.out.println("DataFetcher cancelled.");
return null;
}
data.addChunk(chunk1);
publish(++i);
// And another jdbc data operation....
String chunk2 = someNetworkDataFetching();
if (isCancelled()) {
System.out.println("DataFetcher cancelled.");
return null;
}
data.addChunk(chunk2);
publish(++i);
} catch (Exception ex) {
System.err.println("doInBackground() exception: " + ex);
return null;
}
System.out.println("doInBackground() finished");
return data;
}
}
/**
* Set up the main window.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(label, BorderLayout.CENTER);
// Add a button starting data fetch.
JButton retrieveButton = new JButton("Do it!");
retrieveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fetchData();
}
});
getContentPane().add(retrieveButton, BorderLayout.EAST);
setSize(400, 75);
setLocationRelativeTo(null);
progressBar.setMaximum(2);
}
// Shows new JDialog with a JProgressBar and calls its fetchData()
public void fetchData() {
label.setText("Retrieving data...");
dfp = new DataFetcherProgress(this);
dfp.fetchData();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
// Use jdbc mysql driver
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
return;
}
// Show the Frame
new Test().setVisible(true);
}
});
}
}
About the only thing I might do different is not use the SwingUtilities.invokeLater in the doInBackground method to show the dialog, but maybe use a PropertyChangeListener to monitor the changes to the state property worker.
I would also use the PropertyChangeListener to monitor the changes to the progress property of the worker. Instead of using publish to indicate the progression changes I would use the setProgress method (and getProgress in the PropertyChangeListener)
For example...java swingworker thread to update main Gui
I might also consider creating the UI on a JPanel and adding it to the JDialog rather then extending directory from JDialog as it would give the oppurtunity to re-use the panel in other ways, should you wish...

Dynamically updating Jlist

I've been reading a lot on Swing but I've hit a dead end and I know you can help me.
I've read lots of questions like Updating an JList but still I'm clueless as how to proceed.
My problem is the same as the guy who asked the question I mentioned. I'm making a server and users will access it.
This are my classes.
Server
private string name;
private string dateOfAccess;
#Override
public String toString() {
// TODO Auto-generated method stub
return nombreAmigo;
}
Main
private DefaultListModel listModel = new DefaultListModel();
private JList list=new JList(listModel);
and my ClientHandler
public static List<Conexion> clientes=new ArrayList<Conexion>();
So, I'm going to be filling the clientes list from different threads as they connect to my server and I need to show them in my Jlist. Any suggestions on how to update it? I'm really stuck here
Thanks!
Personally, I would have some kind of "client manager" that is responsible for collating all the clients into a centralised repository. This would be a singleton within your server. It could be queried at any time for a list of currently active users (and other management functions), but there should only ever be one active.
The manager would then fire notification events to interested parties (using an observe pattern).
One of these parties would be your UI. When a "connect" or "disconnect" event is raised, you will need to ensure that this is synced back the Event Dispatching Thread BEFORE you try and update the list model, for example...
public void userConnected(UserManagerEvent evt) { // You would need to define all this yourself...
final Conexion user = evt.getConnection(); // You would need to define this event yourself...
EventQueue.invokeLater(new Runnable() {
public void run() {
listModel.addElement(user);
}
});
}
The actually implementation will come down to what it is you want to achieve and the way you want to achieve it, but this is the basic concept...
Updated with conceptual example
This is a basic, conceptual, example. An event is raised by the button, which simulates (for example) a connection. This event is then sent to the list, via an listener interface, where the model is updated
Events are generated from some other source and the UI is updated when they occur, classic observer pattern
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.w3c.dom.ls.LSInput;
public class UpdateListOnEvent {
public static void main(String[] args) {
new UpdateListOnEvent();
}
public UpdateListOnEvent() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ConnectionEvent {
private Date date;
public ConnectionEvent(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
}
public interface ConnectionListener {
public void connectionEstablished(ConnectionEvent evt);
}
public class TestPane extends JPanel implements ConnectionListener {
private JList list;
private DefaultListModel<String> model;
public TestPane() {
setLayout(new BorderLayout());
model = new DefaultListModel<>();
list = new JList(model);
add(new JScrollPane(list));
EventPane eventPane = new EventPane();
eventPane.addConnectionListener(this);
add(eventPane, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
#Override
public void connectionEstablished(ConnectionEvent evt) {
model.addElement(DateFormat.getDateTimeInstance().format(evt.getDate()));
}
}
public class EventPane extends JPanel {
private List<ConnectionListener> listeners;
private JButton update;
public EventPane() {
listeners = new ArrayList<>(5);
setLayout(new GridBagLayout());
update = new JButton("Update");
update.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// connectionEstablished(new Date());
fireConnectionEstablished(new Date());
}
});
add(update);
}
public void addConnectionListener(ConnectionListener listener) {
listeners.add(listener);
}
public void removeConnectionListener(ConnectionListener listener) {
listeners.remove(listener);
}
protected ConnectionListener[] getConnectionListeners() {
return listeners.toArray(new ConnectionListener[listeners.size()]);
}
protected void fireConnectionEstablished(Date date) {
ConnectionListener[] listeners = getConnectionListeners();
if (listeners != null && listeners.length > 0) {
ConnectionEvent evt = new ConnectionEvent(date);
for (ConnectionListener listener : listeners) {
listener.connectionEstablished(evt);
}
}
}
}
}

JProgressBar Dialog

I'm trying to create a pop up dialog progress bar preferably an Indeterminate but that's not too important. I have been looking through "Oracle's ProgressBar Tutorials" and Google searching but not such luck in getting it to work. I'm pasted my code below of my Action Listener and the dialog will not pop up. Any suggestions? Thanks in advance!
Sorry this is my first post on this site. But how it works is that When I press the create button, it goes out and grab some information from different servers and directories and creates a file for me. That is what the new Project is. Features is a Enumeration I made that are set with the text in the JTextBox when the Create Button. The problem is that this process takes time to process, so I want the a progress bar to show that its processing
private class CreateButton implements ActionListener
{
#Override
public void actionPerformed(ActionEvent arg0) {
class Task extends SwingWorker<Void, Void>
{
#Override
protected Void doInBackground()
{
//Set Variables
for(Feature f : Feature.values())
{
if(f.getComp() != null)
{
f.getVariable().setVariable(((JTextField) f.getComp()).getText());
}
}
new Project(jobs.getSelectedValue().split("-")[0].trim(),
jobs.getSelectedValue().split("-")[1].trim(),
features);
return null;
}
}
ProgressMonitor pm = new ProgressMonitor(display, "Testing...", "", 0, 100);
pm.setProgress(0);
Task task = new Task();
task.execute();
}
}
I was not sure about your SSCCE so I am just posting how JProgressBar usually works.
Read about SwingWorker and JProgressBar
During background process show progress bar. A simple example of how it works is shown.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class MyProgressBarTest {
private static final long serialVersionUID = 1L;
private static JProgressBar progressBar;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyProgressBarTest obj = new MyProgressBarTest();
obj.createGUI();
}
});
}
public void createGUI() {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
final JButton button = new JButton("Progress");
progressBar = new JProgressBar();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
MyCustomProgressBarDialog progressBarObj = new MyCustomProgressBarDialog(progressBar, frame);
progressBarObj.createProgressUI();
MyActionPerformer actionObj = new MyActionPerformer(progressBar, progressBarObj, button);
actionObj.execute();
}
});
panel.add(button);
frame.add(panel);
frame.setTitle("JProgressBar Example");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo(null);
frame.setSize(200, 300);
frame.setVisible(true);
}
}
class MyActionPerformer extends SwingWorker<String, Object> {
JProgressBar fProgressBar;
MyCustomProgressBarDialog progressDialog;
JButton button;
public MyActionPerformer(JProgressBar progressBar, MyCustomProgressBarDialog progressDialog, JButton button) {
this.fProgressBar = progressBar;
this.fProgressBar.setVisible(true);
this.fProgressBar.setIndeterminate(true);
this.button = button;
this.progressDialog = progressDialog;
this.button.setEnabled(false);
}
protected String doInBackground() throws Exception {
calculateResult();
return "Finished";
}
protected void done() {
fProgressBar.setVisible(false);
this.progressDialog.setVisible(false);
this.button.setEnabled(true);
}
public void calculateResult() {
for (int i = 0; i < 500000; i++) {
System.out.println("Progress Bar: " + i);
}
}
}
class MyCustomProgressBarDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static JProgressBar progressBar;
private JFrame motherFrame;
private JLabel label = new JLabel("loading.. ");
private JButton button;
public MyCustomProgressBarDialog(JProgressBar progressBar, JFrame frame) {
this.progressBar = progressBar;
this.motherFrame = frame;
this.button = button;
}
public void createProgressUI() {
add(label, BorderLayout.NORTH);
add(progressBar, BorderLayout.CENTER);
setSize(50, 40);
setAlwaysOnTop(true);
setLocationRelativeTo(motherFrame);
setUndecorated(true);
setVisible(true);
}
}
This comes from the Oracle javadoc for ProgressMonitor:
Initially, there is no ProgressDialog. After the first
millisToDecideToPopup milliseconds (default 500) the progress monitor
will predict how long the operation will take. If it is longer than
millisToPopup (default 2000, 2 seconds) a ProgressDialog will be
popped up.
Note that it doesn't pop up until at least 1/2 second after you create it. Even then, it only pops up if the process is expected to take over 2 seconds.
This is all based on your repeated calls to setProgress(int) and the time between the progression of values across the range you gave it.
I suspect the conditions that cause the dialog to pop up are not being met. Or, perhaps, your program exits before that amount of time goes by.
You need to define attribute
ProgressMonitor pm;
then should create total progress size
int totalProgress = Feature.values().size();
then in the loop just increment count
int counter = 0;
for(Feature f : Feature.values())
{
if (pm.isCanceled()) {
pm.close();
return null;
}
pm.setProgress(counter);
pm.setNote("Task is " + counter*100/totalProgress + "% completed");
counter++;
call the progress monitor
pm = new ProgressMonitor(display, "Testing...", "", 0, totalProgress);
assumed that the most part of the job is done in the loop, if the other part such as project creation takes time then you could add additional percent counts to totalProgress or reset monitor after features completed.

Categories