I have this task run in a thread. The problem is that it freezes the UI every time it is executed. The freeze is longer when the internet is slow. How can I prevent the UI from freezing even if it is still gathering data from the url?
Task<Void> task = new Task<Void>(){
#Override
public Void call() throws Exception {
while (true) {
Platform.runLater(new Runnable() {
#Override
public void run(){
String json = null;
try {
psname = null;
PumpSites n = table.getSelectionModel().getSelectedItem();
psname = n.getPs();
if(psname == "Cubacub")
json = readUrl(""); //read json from thingspeak.com webpage
else if(psname == "Canduman")
json = readUrl("");
} catch (InterruptedIOException iioe)
{
btn1.setTextFill(Color.RED);
btn2.setTextFill(Color.RED);
btn3.setTextFill(Color.RED);
btn4.setTextFill(Color.RED);
btn5.setTextFill(Color.RED);
btn1.setText("NULL");
btn2.setText("NULL");
btn3.setText("NULL");
btn4.setText("NULL");
btn5.setText("NULL");
}
catch (IOException ioe)
{
btn1.setTextFill(Color.RED);
btn2.setTextFill(Color.RED);
btn3.setTextFill(Color.RED);
btn4.setTextFill(Color.RED);
btn5.setTextFill(Color.RED);
btn1.setText("NULL");
btn2.setText("NULL");
btn3.setText("NULL");
btn4.setText("NULL");
btn5.setText("NULL");
}
catch (Exception e1) {
btn1.setTextFill(Color.RED);
btn2.setTextFill(Color.RED);
btn3.setTextFill(Color.RED);
btn4.setTextFill(Color.RED);
btn5.setTextFill(Color.RED);
btn1.setText("NULL");
btn2.setText("NULL");
btn3.setText("NULL");
btn4.setText("NULL");
btn5.setText("NULL");
}
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
for (Item item : page.feeds)
{
det2 = 1;
btn1.setText(item.field1);
btn2.setText(item.field2);
btn3.setText(item.field3);
btn4.setText(item.field4);
btn5.setText(item.field5);
f2 = Float.parseFloat(item.field2);
f3 = Float.parseFloat(item.field3);
//float f5 = Float.parseFloat(item.field5);
if (f2 <= 10.0)
{
btn1.setTextFill(Color.RED);
btn2.setTextFill(Color.RED);
}
else
{
btn1.setTextFill(Color.BLUE);
btn2.setTextFill(Color.BLUE);
}
if (f3 < 0.9 || f3 > 1.2)
{
btn3.setTextFill(Color.RED);
}
else
{
btn3.setTextFill(Color.BLUE);
}
/*if (f5 > 5.0)
{
btn5.setTextFill(Color.RED);
}
else
{
btn5.setTextFill(Color.BLUE);
}*/
btn4.setTextFill(Color.BLUE);
}
if(det2 == 0)
{
btn1.setTextFill(Color.RED);
btn2.setTextFill(Color.RED);
btn3.setTextFill(Color.RED);
btn4.setTextFill(Color.RED);
btn5.setTextFill(Color.RED);
btn1.setText("NULL");
btn2.setText("NULL");
btn3.setText("NULL");
btn4.setText("NULL");
btn5.setText("NULL");
}
det2 = 0;
}
});
Thread.sleep(10000);
}
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
The problem is that it freezes the UI every time it is executed. The freeze is longer when the internet is slow. How can I prevent the UI from freezing even if it is still gathering data from the url?
The UI thread freezes because you are still doing the all the logic on the JavaFX application Thread(Platform.runLater ).
You should do something like this instead:
public Void call() throws Exception
{
while (true)
{
try
{
//get json
} catch(Exception e)
{
Platform.runLater(new Runnable()
{
#Override
public void run()
{
//set buttons color and text here
}
}
}
//Rest of your logic here
}
}
The idea is that everything that is going to modify a UI component from a separate Thread should be handled in the Platform.runLater
If you use a background thread invoke Platform.runLater with a long-running Runnable as parameter, you've effectively achieved nothing. The Runnable is still run on the JavaFX application thread freezing your app.
Instead you should collect all the data on the background thread and process it to the point where you simply need to adjust some properties of the scene. Then you use Platform.runLater to do those updates.
But the good news is that there is a class designed for this scenario that could simplify your code a bit: ScheduledService.
Just make sure that you don't access the GUI in any way from the background thread (neither for reading nor for setting properties).
The following example simplified example should demonstrate the general approach. It calculates some multiples of the value chosen via Spinner on a background thread delaying 10 sec between each calculation:
#Override
public void start(Stage primaryStage) {
Spinner<Integer> spinner = new Spinner(1, 100, 1);
// ensure the value is available in a way that allows synchronisation
final AtomicReference<Integer> input = new AtomicReference<>(spinner.getValue());
spinner.valueProperty().addListener((o, oldValue, newValue) -> input.set(newValue));
final int outputCount = 10;
GridPane root = new GridPane();
root.add(spinner, 0, 0, 2, 1);
// create output grid
Text[] output = new Text[outputCount];
for (int i = 1; i <= output.length; i++) {
Text text = new Text(Integer.toString(spinner.getValue() * i));
output[i - 1] = text;
root.addRow(i, new Text("Value multiplied by " + i + " = "), text);
}
root.setPrefWidth(300);
ScheduledService<int[]> service = new ScheduledService<int[]>() {
#Override
protected Task<int[]> createTask() {
return new Task<int[]>() {
#Override
protected int[] call() throws Exception {
// retrieve value and set it to null to denote a change
// that was already handled to avoid doing unnecessary
// work
Integer value = input.getAndSet(null);
int[] result = null;
if (value != null) {
int valueAsInt = value;
result = new int[outputCount];
for (int i = 0; i < outputCount; i++) {
result[i] = (i + 1) * valueAsInt;
}
}
// simpulate delay
Thread.sleep(2000);
return result;
}
};
}
};
service.valueProperty().addListener((o, oldValue, newValue) -> {
// update GUI
if (newValue != null) {
for (int i = 0; i < outputCount; i++) {
output[i].setText(Integer.toString(newValue[i]));
}
}
});
service.setPeriod(Duration.seconds(10));
// make sure service uses a daemon thread
service.setExecutor(Executors.newSingleThreadScheduledExecutor((Runnable r) -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}));
service.start();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
I recommend looking through the javadoc of ScheduledService to get familiar with it's capabilities. It also allows for things like reacting to exceptions in the task and specifying a backoff strategy.
Related
Hi Im trying to implement an exercise execution list where each exercise should change background color representing that thats the current exercise running every T time for each exercise. I wanted to know how to implement the action of waiting T time until the exercise finish to highlight the next one.
I have something like this, but blocking the thread is not doing the trick.
ArrayList<ExerciseData> exercises;
ExerciseData ex;
int curr = 0;
int cycleSize = warmUpAdapter.getItemCount();
exercises = (ArrayList<ExerciseData>) warmUpAdapter.getExerciseList();
while( curr < cycleSize ){
ex = exercises.get(curr);
ex.setRunning(true);
warmUpAdapter.notifyItemChanged(curr);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ex.setRunning(false);
warmUpAdapter.notifyItemChanged(curr);
curr++;
}
Try to use postDelayed method of Handler:
private static Handler handler = new Handler();
private void doExercise(final int curr){
ArrayList<ExerciseData> exercises = (ArrayList<ExerciseData>) warmUpAdapter.getExerciseList();
if (curr >= exercises.size()){
System.out.println("Finished");
return;
}
final ExerciseData ex = exercises.get(curr);
ex.setRunning(true);
System.out.println("Running exercise " + curr);
warmUpAdapter.notifyItemChanged(curr);
handler.postDelayed(new Runnable() {
#Override
public void run() {
ex.setRunning(false);
warmUpAdapter.notifyItemChanged(curr);
doExercise(curr + 1);
}
}, 1000);
}
... call later to start exercises:
doExercise(0);
i am playing some animation from my apps by using infinite loop, working well. i need to make wait my thread when user want and again start when user want. For that i used wait and notify thread by clicking my root layout, first click make my thread wait and second click make my thread run. That also work as i want.
My problem is when i make click fast, it means when i make wait and also make notify instantly my Apps get hang.
So how I can fixed that problem???
below is my Code:
public class AboutC implements Initializable {
public VBox mainLayout;
#FXML
private
Label nameLvl = new Label();
#FXML
private
Label rollLvl = new Label();
#FXML
private
Label batchLvl = new Label();
#FXML
private
Label depLvl = new Label();
#FXML
private
Label uniLvl = new Label();
#FXML
private Circle circle = new Circle();
private int count = 0;
private boolean run = true;
private Thread thread;
private Task task;
private FadeTransition fd;
private RotateTransition rt;
private Timeline tm;
#Override
public void initialize(URL location, ResourceBundle resources) {
ArrayList<AboutDevelopers> list = new ArrayList<>();
list.add(....)
fd = new FadeTransition(Duration.seconds(4), mainLayout);
fd.setFromValue(0.2);
fd.setToValue(1.0);
fd.setCycleCount(2);
rt = new RotateTransition(Duration.seconds(4), circle);
rt.setByAngle(360);
rt.setAutoReverse(true);
rt.setCycleCount(2);
KeyFrame keyFrame = new KeyFrame(Duration.seconds(4), new KeyValue(circle.radiusProperty(), 0));
tm = new Timeline(keyFrame);
tm.setCycleCount(2);
tm.setAutoReverse(true);
task = new Task<Void>() {
#Override
synchronized public Void call() throws Exception {
int i = 0;
while (true) {
if (run) {
Platform.runLater(() -> {
nameLvl.setText(list.get(count).getName());
rollLvl.setText("Roll: " + list.get(count).getRoll());
batchLvl.setText("Batch: " + list.get(count).getBatch());
depLvl.setText("Department: " + list.get(count).getDepartment());
uniLvl.setText(list.get(count).getUniversity());
circle.setFill(new ImagePattern(new Image(list.get(count).getImagePath())));
fd.play();
rt.play();
tm.play();
count++;
if (count >= list.size())
count = 0;
});
sleep(10000);
} else
wait();
}
}
};
thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
void setStage(Stage stage) {
stage.setOnCloseRequest(event -> {
thread.interrupt();
});
}
public void playThread(){
if (run) {
run = false;
} else {
if(!run){
synchronized (task) {
task.notify();
}
}
run = true;
}
}
}
run is not volatile and is written to outside of synchronized blocks. This means the task may never see the updated value.
Using Thread.sleep(10000) you do not release the lock on the Task which means the following could happen:
The task starts sleeping
The playThread method changes run to false
The playThread method is invoked again and tries to aquire a lock on the task object which the task still keeps itself leading to the calling thread to be blocked for up to 10 sec
To fix these issues, modify the run field only from a synchronized block and use wait with a timeout instead of sleep:
while (true) {
if (run) {
Platform.runLater(() -> {
nameLvl.setText(list.get(count).getName());
rollLvl.setText("Roll: " + list.get(count).getRoll());
batchLvl.setText("Batch: " + list.get(count).getBatch());
depLvl.setText("Department: " + list.get(count).getDepartment());
uniLvl.setText(list.get(count).getUniversity());
circle.setFill(new ImagePattern(new Image(list.get(count).getImagePath())));
fd.play();
rt.play();
tm.play();
count++;
if (count >= list.size())
count = 0;
});
wait(10000);
} else
wait();
}
public void playThread(){
synchronized (task) {
run = !run;
if (run) {
task.notify();
}
}
}
This means however starting and stoping the task may speed up the update frequency...
Alternative:
Use a ScheduledExecutorService to schedule updates regularly:
// TODO: shut this down after you're done with it???
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
});
#Override
public void initialize(URL location, ResourceBundle resources) {
...
startTask();
}
private final Runnable updateRunnable = () -> {
Platform.runLater(() -> {
nameLvl.setText(list.get(count).getName());
rollLvl.setText("Roll: " + list.get(count).getRoll());
batchLvl.setText("Batch: " + list.get(count).getBatch());
depLvl.setText("Department: " + list.get(count).getDepartment());
uniLvl.setText(list.get(count).getUniversity());
circle.setFill(new ImagePattern(new Image(list.get(count).getImagePath())));
fd.play();
rt.play();
tm.play();
count++;
if (count >= list.size())
count = 0;
}
});
};
private ScheduledFuture scheduledFuture;
private void startTask() {
scheduledFuture = executor.scheduleWithFixedDelay(updateRunnable, 0, 10000, TimeUnit.MILLISECONDS);
}
public void playThread() {
if (scheduledFuture == null) {
// nothing running currently
startTask();
} else {
scheduledFuture.cancel();
scheduledFuture = null;
}
}
Or in a way more suitable to JavaFX
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(10), evt -> {
nameLvl.setText(list.get(count).getName());
rollLvl.setText("Roll: " + list.get(count).getRoll());
batchLvl.setText("Batch: " + list.get(count).getBatch());
depLvl.setText("Department: " + list.get(count).getDepartment());
uniLvl.setText(list.get(count).getUniversity());
circle.setFill(new ImagePattern(new Image(list.get(count).getImagePath())));
fd.play();
rt.play();
tm.play();
count++;
if (count >= list.size())
count = 0;
}
});
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
if (timeline.getStatus == Animation.Status.RUNNING) {
timeline.stop();
} else {
timeline.play();
}
Is there any way of running a handler inside a loop?
I have this code but is not working as it does not wait for the loop but executes the code right way:
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
//
for (int i = 1; i < 6; i++) {
handler.postDelayed(this, 5000);
}
}
};
// trigger first time
handler.postDelayed(runnable, 0);
Of course when I move the post delayed outside the loop works but it does not iterate nor execute the times I need:
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
//
for (int i = 1; i < 6; i++) {
}
// works great! but it does not do what we need
handler.postDelayed(this, 5000);
}
};
// trigger first time
handler.postDelayed(runnable, 0);
SOLUTION FOUND:
I need to use asyntask along with Thread.sleep(5000) in the doInBackground method:
class ExecuteAsyncTask extends AsyncTask<Object, Void, String> {
//
protected String doInBackground(Object... task_idx) {
//
String param = (String) task_idx[0];
//
Log.d(TAG, "xxx - iter value started task idx: " + param);
// stop
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//
Log.d(TAG, "xxx - iter value done " + param);
return " done for task idx: " + param;
}
//
protected void onPostExecute(String result) {
Log.d(TAG, "xxx - task executed update ui controls: " + result);
}
}
for(int i = 0; i < 6; i ++){
//
new ExecuteAsyncTask().execute( String.valueOf(i) );
}
Instead of using a for loop, you can let the Runnable instance call itself for a specific number of times. These calls will be posted to UI thread queue so, keep that in mind. Also, since the delay is quite large, make sure the event is still needed when you trigger it next time.
The following code should do it:
final Handler handler = new Handler();
int count = 0;
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "Run test count: " + count);
if (count++ < 5) {
handler.postDelayed(this, 5000);
}
}
};
// trigger first time
handler.post(runnable);
Here is a simple logic I made, without moving the for loop inside runnable.
for(int i = 1; i<=5; i++){
...
new Handler().postDelayed(() -> myFunctionToExecute() , i * 1000);
}
So whenever the loop iterates, it just extends the handler delay. And this way, you may achieve. I was searching for something similar, couldn't find anything, because in my case I already did the implementation of for loop, moving it inside the run() creates a mess
My solution to this problem if anyone has simmilar issues:
int count = 0;
public static void method(param1, param2, param3) {
Runnable r = () -> { //put method inside runnable
View view = listView.getChildAt(position); //action to be complete
if (view != null) { //if action is successfully complete
view.setSelected(true); //do something with this
} else { //do a looper
if (count < 10) { //limited looper to certain number
count++;
method(param1, param2, param3); //run the method again
}
};
Handler h = new Handler(); //create a new Handler and post above thread with it
h.postDelayed(r, 300);
}
Basically, I have created an if-else statement where else statement runs the same method with postDelayed() again for a limited number of trials.
This can be another solution
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i;
public void run() {
for (i = 1; i < 6; i++) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
}
}, 0);
//Add some downtime
SystemClock.sleep(5000);
}
}
};
new Thread(runnable).start();
So my JProgressBar I have set up doesn't work the way I want it. So whenever I run the program it just goes from 0 to 100 instantly. I tried using a ProgressMonitor, a Task, and tried a SwingWorker but nothing I tried works.
Here is my program:
int max = 10;
for (int i = 0; i <= max; i++) {
final int progress = (int)Math.round(
100.0 * ((double)i / (double)max)
);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
jProgressBar2.setValue(progress);
}
});
}
#MadProgrammer Here is my attempt at making a swing worker and writing each name to the document and updating the progress bar. The program gets to around 86 percent and stops, never creating the finished document. The program creates a blank document. Here are the two methods first is the SwingWorker object I made:
public class GreenWorker extends SwingWorker<Object, Object> {
#Override
protected Object doInBackground() throws Exception {
int max = greenList.size();
XWPFParagraph tmpParagraph;
XWPFRun tmpRun;
FileInputStream file =
new FileInputStream(location + "GreenBandList.docx");
gDocument = new XWPFDocument(OPCPackage.open(file));
for (int i = 0; i < max; i++) {
tmpParagraph = gDocument.getParagraphs().get(0);
tmpRun = tmpParagraph.createRun();
if (greenList.get(i).length() == 1) {
tmpRun.setBold(true);
tmpRun.setText(greenList.get(i));
tmpRun.setBold(false);
} else {
tmpRun.setText(greenList.get(i));//Write the names to the Word Doc
}
int progress = Math.round(((float) i / max) * 100f);
setProgress(progress);
}
return null;
}
}
And here is the code for the button that starts it and has my property change event.
private void GenerateGreenList() throws IOException, InterruptedException {
//Need to fix the bug that removes the Letter Header in Yellow Band list
//********************************************************************\\
//Delete the old list and make a new one
File templateFile = new File(location + "\\backup\\GreenTemplate.docx");
FileUtils.deleteQuietly(new File(location + "GreenBandList.docx"));
FileUtils.copyFile(templateFile, new File(location +
"GreenBandList.docx"));
//Get the New Entries
String[] entries = jTextPane3.getText().split("\n");
for (String s : entries) {
if (s != null) {
greenList.add(s);
}
}
//Resort the list
Collections.sort(greenList);
//Write the names to the document
GreenWorker worker = new GreenWorker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
jProgressBar2.setValue((Integer) evt.getNewValue());
}
}
});
worker.execute();
if (worker.isDone()) {
try {
gDocument.write(new FileOutputStream(new File(location + "GreenBandList.docx")));
////////////////////////////////////////////////////////////
} catch (IOException ex) {
Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "Green Band List Created!");
jProgressBar2.setValue(0);
}
}
I used the property change listener from one of your other posts but I don't really understand what the one you wrote does or what it does in general?
Swing is a single threaded environment, that is, there is a single thread which is responsible for processing all the events that occur within the system, including repaint events. Should anything block this thread for any reason, it will prevent Swing from processing any new events, including, repaint events...
So all this ...
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex); }
jProgressBar2.setValue(progress);
}
});
Is constantly pausing the Event Dispatching Thread, preventing it from actually doing any updates (or at least spacing them randomly)...
It's also likely that your outer loop is been run from within the context of the EDT, meaning that until it exists, nothing in the Event Queue will be processed. All your repaint requests will be consolidated down to a single paint request and voila, instant filled progress bar...
You really should use a SwingWorker - I know you said you tried one, but you've not shown any code as to your attempt in this regards, so it's difficult to know why it didn't work, however...
SwingWorker and JProgressBar example
SwingWorker and JProgressBar example
SwingWorker and JProgressBar example
SwingWorker and JProgressBar example
SwingWorker and dual welding JProgressBar example
SwingWorker and JProgressBar example
And forgive me if we haven't said this a few times before :P
You are evoking Thread.sleep inside the EvokeLater which means that it is running on another thread than your for loop. i.e., your for loop is completing instantaneously (well, however long it takes to loop from 1 to 100, which is almost instantaneously).
Move Thread.sleep outside of EvokeLater and it should work as you intend.
int max = 10;
for (int i = 0; i <= max; i++) {
final int progress = (int)Math.round(
100.0 * ((double)i / (double)max)
);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
jProgressBar2.setValue(progress);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
Edit: agree with #MadProgrammer. It appears this is just an illustrative question, but you should make sure whatever you're trying to accomplish here you use a SwingWorker for.
I have JTabbedPane with 4 tabs. JtabbedPane is situated on a JLayeredPane. 1st and 4th tab contain JTable with custom models. Each of the tables is being refreshed every 5-10 seconds.
When 1st tab is active, and JTable on 4th has just finished refreshing, I can see content of the 4th on the 1st. Look at the screenshot.
When I click on the other tab, or minimize window, that strange effect is gone. Till the next refresh of that table on 4th tab. Refreshing is done using Future<> object.
I used Swing GUI builder in Netbeans, so I have huge amount of code. Would post any piece which could be useful.
I tried to revalidate jTabbedPane, is had no effect. Both tables and jScrollPanes has opaque property set to true. So I tried to use SwingUtilities.invokeLater(). It helped a little bit - now first content update goes well, but later - the same problem.
2nd table model has method to update it's content
public void setData(LinkedList<Object[]> __rows) {
NewDevsTableModel.__rows = __rows;
fireTableDataChanged();
}
It is used here (I added SwingUtilities here)
static class checkNew implements Callable<Boolean> {
#Override
public Boolean call() {
ServiceMessage sm = ServiceMessage.getNewList();
try {
connect();
os.write(sm.serialize());
for (int i=0; i<10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
if (is.available() > 0) {
break;
}
if (i == 9) {
disconnect();
return false;
}
}
byte[] actByte = new byte[is.available()];
is.read(actByte);
try {
sm = ServiceMessage.Deserialize(actByte); //may be there are no new devices
if (sm.getType() == ServiceMessageType.NODATA) {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
return true;
} else {
return false; //wrong answer type
}
} catch (ClassCastException | StreamCorruptedException e) {
//remember selection and scroll
final int scroll = MainWindow.jScrollPane3.getVerticalScrollBar().getValue();
final int[] rows = MainWindow.newDevsTable.getSelectedRows();
int col = MainWindow.devicesTable.getSelectedColumn();
String[] parts = new String(actByte).split("\n");
final LinkedList<Object[]> l = new LinkedList();
for (int i=0; i<parts.length; i++) {
String[] dev = parts[i].split(";", -1);
String descr = dev[2];
boolean iptype = (!dev[3].equals("-"));
String address = dev[4];
boolean atmtype = (dev[5].equals("+"));
if (MainWindow.newDevsTable.getRowCount() >= (i+1)) {
if ((MainWindow.newDevsTable.getValueAt(i, 4) != null) && !MainWindow.newDevsTable.getValueAt(i, 4).equals("")) {
descr = MainWindow.newDevsTable.getValueAt(i, 4).toString();
}
}
Object[] o = {dev[0], dev[1], MainWindow.language[180], MainWindow.language[4], descr, iptype, address, atmtype};
l.add(o);
}
if (!l.isEmpty()) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
MainWindow.newDevsPanel.setVisible(true);
MainWindow.jTabbedPane1.setEnabledAt(3, true);
((NewDevsTableModel)MainWindow.newDevsTable.getModel()).setData(l);
ButtonColumn buttonColumn = new ButtonColumn(MainWindow.newDevsTable, addAction, 2, true);
buttonColumn = new ButtonColumn(MainWindow.newDevsTable, rejAction, 3, false);
//put selection back
for (int i=0; i<rows.length; i++) {
MainWindow.newDevsTable.addRowSelectionInterval(rows[i], rows[i]);
}
MainWindow.jScrollPane3.getVerticalScrollBar().setValue(scroll);
}
});
} else {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
}
return true;
}
} catch (IOException e) {
disconnect();
return false;
} catch (ClassNotFoundException e) {
return false;
}
}
}
I submit the task this way
public static Future<Boolean> checkNewDevices() {
final Future<Boolean> task;
task = service.submit(new checkNew());
return task;
}
To refresh automatically I use separate thread
public class CheckNewPassThread extends Thread {
int pause = 10000;
#Override
public void run() {
for (;;) {
HostConnection.checkNewDevices();
try {
Thread.sleep(pause);
} catch (InterruptedException e) {}
}
}
}
Which is started when the window is opened
private void formWindowOpened(java.awt.event.WindowEvent evt) {
HostConnection.getData();
HostConnection.getDeviceAddress();
RefreshData refreshThread = new RefreshData();
refreshThread.start();
new CheckNewPassThread().start();
}
OMG, the problem was in calling jTabbedPane.setEnabledAt(3, true) to already enabled tab. Swing is fascinating