Reputation: 41
i have checkbox and i want
Below is event of checkbox :-
final JCheckBox rfh = new JCheckBox("Auto Refresh");
toolbar.add(rfh);
toolbar.setAlignmentX(0);
rfh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
while ( rfh.isSelected() ) {
if (rfh.isSelected()) {
// ((JCheckBox)evt.getSource()).isSelected()
JOptionPane.showMessageDialog(toolbar,"thank you for using java");
Thread.sleep(5 * 1000);
} else {
JOptionPane.showMessageDialog(toolbar,"not selected");
}
}
} catch (Exception e) {
}
}
});
Upvotes: 1
Views: 623
Reputation: 347214
Start by taking a look at:
Basically, Swing is a single threaded environment, so don't try and use a loop and Thread.sleep
within the ActionPerformed
method.
The two easiest solutions would either be...
Timer
A Swing Timer
will allow you to setup a regular scheduled call back. This callback will be executed within the context of the Event Dispatching Thread, making it great for updating the UI from.
It can easily be started and stopped.
The draw back is, it is notified within the context of the EDT, which makes it a poor choice for making calls to the database, which could cause the program to "stutter" every time it is called...
SwingWorker
A SwingWorker
provides the means to perform work in the background, but provides functionality that makes it easy to make updates to the UI.
Basically, you would need to setup a loop of some kind (within the workers doInBackground
method) and use Thread.sleep
to wait for a prescribed period of time. Once Thread.sleep
returns, you would make your call to the database, built a your data model and pass it to the publish
method.
Within the process
method, which is called within the context of the EDT, you would process these results and update your table model accordingly...
The drawback with this is you will need to devise the means by which the worker can be stopped (or turned off) and, if you're so inclined, restarted...
Upvotes: 2