I have lot of things implemented in ComponentAdapter of Java. Since it does loading data from database and displaying in JTable, I added it into another thread. I will show you one method which is being called by such ComponentAdapter
private class DisplayInitialRevenue_Thread implements Runnable
{
#Override
public void run()
{
displayInitialRevenue_Method();
}
}
private void displayInitialRevenue_Method()
{
//Get the dates from the combo
String selectedCouple = revenueYearCombo.getSelectedItem().toString();
if(selectedCouple.equals("Select Year"))
{
return;
}
String[] split = selectedCouple.split("/");
//Related to DB
double totalamountInvested;
//Get data from the database
dbConnector = new DBHandler();
dbConnector.makeConnection();
DefaultTableModel model = (DefaultTableModel) initialRevenueTable.getModel();
model.setRowCount(0);
ResultSet selectAllDetails = dbConnector.selectAllDetails("SQL CODE HERE ");
try
{
if(selectAllDetails.isBeforeFirst()==false)
{
JOptionPane.showMessageDialog(null,"This table is empty");
}
else
{
while(selectAllDetails.next())
{
String clientName = selectAllDetails.getString("Client Name");
String providerName = selectAllDetails.getString("Provider Name");
Double amountInvested = selectAllDetails.getDouble("Invest_Amount");
//Get Other Data
//Update the table
Object[]row = {dateS,clientName,providerName,amountInvested};
model.addRow(row);
//Get the total
amountInvested = amountInvested+amountInvested;
}
//Add the sum
Object[]blankRow = {null,null,null,null};
model.addRow(blankRow);
Object[]row = {dateS,clientName,providerName,amountInvested};
}
}
catch(SQLException sql)
{
JOptionPane.showMessageDialog(null,sql.getLocalizedMessage());
}
}
And, this above thread can be called in 3 ways. That is by ItemListener attached to a JComboBox, ActionListener attached to a JMenuand ComponentListener.
ComponentListener
private class DisplayInitialRevenue extends ComponentAdapter
{
public void componentShown(ComponentEvent e)
{
formMemorizer = FormMemorizer.Initial_Revenue;
//displayInitialRevenue_Method();
DisplayInitialRevenue_Thread t = new DisplayInitialRevenue_Thread();
t.run();
}
}
ItemListener
private class RevenueYearComboAction implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int selection = formMemorizer;
if(selection==-1)
{
return;
}
else if(selection==FormMemorizer.Initial_Revenue)
{
//displayInitialRevenue_Method();
DisplayInitialRevenue_Thread t = new DisplayInitialRevenue_Thread();
t.run();
}
}
}
I have lot of these kind of methods to get the data from the database and feed the JTables and take data from GUI and save in database.
Now my question is, all of these are freezing sometimes, whenever a database call occurred. I thought it is bcs of Thread issue so I made the above DisplayInitialRevenue_Thread to call displayInitialRevenue_Method() as a test. Then I only invoked the area related to the call this method but it still freezes sometimes! My other database methods are not in separate threads, but this is method is, so why even calling "only" this method lead this to freeze? It is in a thread!
For side note, I am in Java 8, using MySQL Server version: 5.6.16 - MySQL Community Server (GPL) which comes with XAMPP.
Call t.start() to start a new Thread, calling Thread#run does nothing more then calls the run method of the Thread within the same thread context...
Having said that, Swing is not thread safe, Swing requires that all updates to the UI are made from within the context of the Event Dispatching Thread. Instead of using a Thread, you should consider using a SwingWorker, which allows you to execute long running tasks in a background thread, but which provides easy to use publish/process methods and calls done when it completes, which are executed within the context of the EDT for you.
See Worker Threads and SwingWorker for more details
Related
I have lot of things implemented in ComponentAdapter of Java. Since it does loading data from database and displaying in JTable, I added it into another thread. I will show you one method which is being called by such ComponentAdapter
private class DisplayInitialRevenue_Thread implements Runnable
{
#Override
public void run()
{
displayInitialRevenue_Method();
}
}
private void displayInitialRevenue_Method()
{
//Get the dates from the combo
String selectedCouple = revenueYearCombo.getSelectedItem().toString();
if(selectedCouple.equals("Select Year"))
{
return;
}
String[] split = selectedCouple.split("/");
//Related to DB
double totalamountInvested;
//Get data from the database
dbConnector = new DBHandler();
dbConnector.makeConnection();
DefaultTableModel model = (DefaultTableModel) initialRevenueTable.getModel();
model.setRowCount(0);
ResultSet selectAllDetails = dbConnector.selectAllDetails("SQL CODE HERE ");
try
{
if(selectAllDetails.isBeforeFirst()==false)
{
JOptionPane.showMessageDialog(null,"This table is empty");
}
else
{
while(selectAllDetails.next())
{
String clientName = selectAllDetails.getString("Client Name");
String providerName = selectAllDetails.getString("Provider Name");
Double amountInvested = selectAllDetails.getDouble("Invest_Amount");
//Get Other Data
//Update the table
Object[]row = {dateS,clientName,providerName,amountInvested};
model.addRow(row);
//Get the total
amountInvested = amountInvested+amountInvested;
}
//Add the sum
Object[]blankRow = {null,null,null,null};
model.addRow(blankRow);
Object[]row = {dateS,clientName,providerName,amountInvested};
}
}
catch(SQLException sql)
{
JOptionPane.showMessageDialog(null,sql.getLocalizedMessage());
}
}
And, this above thread can be called in 3 ways. That is by ItemListener attached to a JComboBox, ActionListener attached to a JMenuand ComponentListener.
ComponentListener
private class DisplayInitialRevenue extends ComponentAdapter
{
public void componentShown(ComponentEvent e)
{
formMemorizer = FormMemorizer.Initial_Revenue;
//displayInitialRevenue_Method();
DisplayInitialRevenue_Thread t = new DisplayInitialRevenue_Thread();
t.run();
}
}
ItemListener
private class RevenueYearComboAction implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int selection = formMemorizer;
if(selection==-1)
{
return;
}
else if(selection==FormMemorizer.Initial_Revenue)
{
//displayInitialRevenue_Method();
DisplayInitialRevenue_Thread t = new DisplayInitialRevenue_Thread();
t.run();
}
}
}
I have lot of these kind of methods to get the data from the database and feed the JTables and take data from GUI and save in database.
Now my question is, all of these are freezing sometimes, whenever a database call occurred. I thought it is bcs of Thread issue so I made the above DisplayInitialRevenue_Thread to call displayInitialRevenue_Method() as a test. Then I only invoked the area related to the call this method but it still freezes sometimes! My other database methods are not in separate threads, but this is method is, so why even calling "only" this method lead this to freeze? It is in a thread!
For side note, I am in Java 8, using MySQL Server version: 5.6.16 - MySQL Community Server (GPL) which comes with XAMPP.
Call t.start() to start a new Thread, calling Thread#run does nothing more then calls the run method of the Thread within the same thread context...
Having said that, Swing is not thread safe, Swing requires that all updates to the UI are made from within the context of the Event Dispatching Thread. Instead of using a Thread, you should consider using a SwingWorker, which allows you to execute long running tasks in a background thread, but which provides easy to use publish/process methods and calls done when it completes, which are executed within the context of the EDT for you.
See Worker Threads and SwingWorker for more details
basically, I have this code which was initially working with console i/o now I have to connect it to UI. It may be completely wrong, I've tried multiple things although it still ends up with freezing the GUI.
I've tried to redirect console I/O to GUI scrollpane, but the GUI freezes anyway. Probably it has to do something with threads, but I have limited knowledge on it so I need the deeper explanation how to implement it in this current situation.
This is the button on GUI class containing the method that needs to change this GUI.
public class GUI {
...
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.startTest(index, idUser);
}
});
}
This is the method startTest from another class which contains instance of Question class.
public int startTest() {
for (int i = 0; i < this.numberofQuestions; i++) {
Question qt = this.q[i];
qt.askQuestion(); <--- This needs to change Label in GUI
if(!qt.userAnswer()) <--- This needs to get string from TextField
decreaseScore(1);
}
return actScore();
}
askQuestion method:
public void askQuestion() {
System.out.println(getQuestion());
/* I've tried to change staticaly declared frame in GUI from there */
}
userAnswer method:
public boolean userAnswer() {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
if( Objects.equals(getAnswer(),userInput) ) {
System.out.println("Correct");
return true;
}
System.out.println("False");
return false;
}
Thanks for help.
You're correct in thinking that it related to threads.
When you try executing code that will take a long time to process (eg. downloading a large file) in the swing thread, the swing thread will pause to complete execution and cause the GUI to freeze. This is solved by executing the long running code in a separate thread.
As Sergiy Medvynskyy pointed out in his comment, you need to implement the long running code in the SwingWorker class.
A good way to implement it would be this:
public class TestWorker extends SwingWorker<Integer, String> {
#Override
protected Integer doInBackground() throws Exception {
//This is where you execute the long running
//code
controller.startTest(index, idUser);
publish("Finish");
}
#Override
protected void process(List<String> chunks) {
//Called when the task has finished executing.
//This is where you can update your GUI when
//the task is complete or when you want to
//notify the user of a change.
}
}
Use TestWorker.execute() to start the worker.
This website provides a good example on how to use
the SwingWorker class.
As other answers pointed out, doing heavy work on the GUI thread will freeze the GUI. You can use a SwingWorker for that, but in many cases a simple Thread does the job:
Thread t = new Thread(){
#Override
public void run(){
// do stuff
}
};
t.start();
Or if you use Java 8+:
Thread t = new Thread(() -> {
// do stuff
});
t.start();
I can load data from query result in JTable nicely.
SELECT * FROM 'customer info';
Make a result set and place to JTable is easy to handle.
But problem is, as my database table is so big and it takes so much time to load. My application totally freeze until current task complete. I know swing worker can perform a background task. I study this, but i find no any appropriate solution in my case. Because i already write a lot of function in basic way.
So finally what i need?
I need a Class, design with swing worker by which i can easily use it's object anywhere in my application. suppose i send my query string and JTable in this class constructor. Then it automatically starts a background thread to make result set and place it in JTable.
ok now its work in my case :) here is my own solution ....
public class UsableSwingWorkerThread extends SwingWorker<ResultSet, Object> {
JTable table;
String query;
public UsableSwingWorkerThread(JTable table, String query) {
this.table = table;
this.query = query;
}
#Override
protected ResultSet doInBackground() throws Exception {
return DatabaseFunctionClass.con.prepareStatement(query).executeQuery();
}
void loadTable(TableModel tb) {
new UsableDefaultLoadTable(tb, table);
}
#Override
protected void done() {
try {
loadTable(DbUtils.resultSetToTableModel(get()));
} catch (Exception ignore) {
StaticAccess.showMassageDialog(StaticAccess.mainFrame, "Fail to load. try again later..", ignore);
}
}
}
I come from .NET environment where event listening is pretty easy to implement even for a beginner. But this time I have to do this in Java.
My pseudo code:
MainForm-
public class MainForm extends JFrame {
...
CustomClass current = new CustomClass();
Thread t = new Thread(current);
t.start();
...
}
CustomClass-
public class CustomClass implements Runnable {
#Override
public void run()
{
//...be able to fire an event that access MainForm
}
}
I found this example but here I have to listen for an event like in this other one. I should mix them up and my skill level in Java is too low.
Could you help me elaborating a optimal solution?
I think that what you are looking for is SwingWorker.
public class BackgroundThread extends SwingWorker<Integer, String> {
#Override
protected Integer doInBackground() throws Exception {
// background calculation, will run on background thread
// publish an update
publish("30% calculated so far");
// return the result of background task
return 9;
}
#Override
protected void process(List<String> chunks) { // runs on Event Dispatch Thread
// if updates are published often, you may get a few of them at once
// you usually want to display only the latest one:
System.out.println(chunks.get(chunks.size() - 1));
}
#Override
protected void done() { // runs on Event Dispatch Thread
try {
// always call get() in done()
System.out.println("Answer is: " + get());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Of course when using Swing you want to update some GUI components instead of printing things out. All GUI updates should be done on Event Dispatch Thread.
If you want to only do some updates and the background task doesn't have any result, you should still call get() in done() method. If you don't, any exceptions thrown in doInBackground() will be swallowed - it is very difficult to find out why the application is not working.
In my Java GUI app I have a JButton and when clicked it calls a function to connect to a database, then calls a function to clear a table in the DB, then calls a function that reads text from one file and loads variables, which calls a function that reads text from another file, compares the data from both and then calls a function to either update or insert data in the DB, all of that works fine.
However my question is related to the JButton, when its clicked I want to run a Indeterminate progress bar just so the user knows work is being done and then right before it leaves the the action listener setIndeterminate to false and set the value of the progress bar to 100(complete), but in my case when you click the button it stays in the clicked state and the progress bar freezes.
What should I implement to prevent this? threading possibly? but Im quite new to threading in java. here is my action listener:
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
dbConnect(); //connects to DB
clearSchedules(); // deletes data in tables
readFile(); // reads first file and calls the other functions
dbClose();// closes the DB
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}
}
}
On a side note, I would like to have the action bar actually move as the the program progresses but I wasnt sure how to monitor its progress.
Thanks, Beef.
UPDATE here is my example of SwingWorker and how I used it:
Declared globally
private functionWorker task;
private abstract class functionWorker extends SwingWorker {
public void execute() {
try {
dbConnect();
} catch (SQLException e) {
e.printStackTrace();
}
clearSchedules();
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
dbClose();
}
}
Inside my actionPerformed method
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
task.execute();
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}
The problem is probably related to connecting to doing expensive operations in the UI thread (connecting to a database, reading from a file, calling other functions). Under no circumstances should you call code that uses excessive CPU time from the UI thread, as the entire interface can't proceed while it is executing your code, and it results in a 'dead' looking application, with components remaining in their state at the time before an expensive operation until completion. You should execute another thread, do the expensive work in that, and then use a SwingUtilities.invokeLater(Runnable doRun) with a passed runnable where you'd update the progress.
There may be synchronisation issues relating to the states of components, but you can fix these later.
Could I create the new thread when the action is performed and call the new functions in the thread, or should I do the threading within the actual function itself?
You can start a SwingWorker from your button's handler, as shown here. A related example implementing Runnable is seen here.
One method to handle progressbars are to extend SwingWorker in a class.
SwingWorker takes care of running background tasks for you and so you do not have to implement your own threading that can end up in unknown issues.
To begin with, your class that takes care of progress bar UI should implement PropertyChangeListener
And implement public void propertyChange(PropertyChangeEvent evt) { - to update the progressbar status based on a global variable.
The background task class should look like the following(this could be an inner class) :
class ProgressTask extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
//handle your tasks here
//update global variable to indicate task status.
}
#Override
public void done() {
//re-enabled your button
}
}
on your button's event listener :
public void actionPerformed(ActionEvent evt) {
//disable your button
//Create new instance of "ProgressTask"
//make the task listen to progress changes by task.addPropertyChangeListener(this);
//calll task.execute();
}
I have tried to water down code example, you would have to read some tutorial to understand how all these pieces fit together. However, the main point is do not code your Threads, instead use SwingWorker
progressBar.setIndeterminate(true);
progressBar.setValue(0);
dbConnect(); //connects to DB
progressBar.setIndeterminate(true);
progressBar.setValue(10);
clearSchedules(); // deletes data in tables
progressBar.setIndeterminate(true);
progressBar.setValue(50);
readFile(); // reads first file and calls the other functions
progressBar.setIndeterminate(true);
progressBar.setValue(75);
dbClose();// closes the DB
progressBar.setIndeterminate(false);
progressBar.setValue(100);
You will need to tell the progress bar how much progress has been made because it does not know the percentage completed. Better yet, write a method that updates and repaints the progress bar rather than repeating the method calls here.
updateProgressBar(int progress, boolean isDeterminate, String msg){};
You will also need to make sure that your specific button is firing the action performed.
class IvjEventHandler implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() == JMyPanel.this.getJButtonUpdate())
connEtoC1(e);
};
};
The connEtoC1(e); should execute a controller class or SwingWorker rather than firing from the GUI