My program is to ping a host infinitely and display each ping result on the GUI as RED/GREEN. Here, 'res' is a label that changes its text and background based on the ping result.
The issue is that when i use while(), the GUI becomes unresponsive and the colour of the label does not change, while the ping service continues. How do i solve this issue??
while (true) {
try {
boolean status = InetAddress.getByName(host).isReachable(timeOut);
if (status == true) {
res.setText("ON");
res.setBackground(Color.GREEN);
} else {
res.setText("OFF");
res.setBackground(Color.RED);
}
} catch (IOException ex) {
}
Start by taking a look at Concurrency in Swing
Essentially, from your description, you are blocking the Event Dispatching Thread, preventing it from process new events, including paint events.
Swing is also NOT thread safe, this means you should not update the UI from outside of the context of the EDT.
In this case, you could use a
SwingWorker
to perform the physical "ping" from within thedoInBackground
method and make use of thepublish
/process
methods to update the UI.See Worker Threads and SwingWorker for more details