GUI blocked after checked a JcheckBox

simplo

Mitglied
Hi guys ,
i wrote a progamm to print messages while the Jchekbox is selected , but the problem is : my gui completely blocked when i check my box (also my jCheckBox is no more selectable). can someone tell me how to resolve the problem ? . here is my code : The red marked code block the gui ( i think)

private void jCheckBox1ItemStateChanged(java.awt.event.ItemEven t evt) {

boolean state = jCheckBox1.isSelected();
if(state ){
try {
send("start tick");
} catch (IOException ex) {
Logger.getLogger(DiagClient.class.getName()).log(L evel.SEVERE, null, ex);
}
try {
do{
socket.receive(buffer);

recvMsg = new String (inData ,0 ,buffer.getLength());
System.out.println(recvMsg);
}
while(buffer.getLength() !=0);

} catch (IOException ex) {
Logger.getLogger(DiagClient.class.getName()).log(L evel.SEVERE, null, ex);
}


}
 
All Swing events are processed by the "Event Dispatch Thread". This thread is also executing the "jCheckBox1ItemStateChanged" mehtod. (This Thread is also responsible for painting, by the way). So as long as you are waiting for the socket, no events can be processed, and no painting can be done, because the thread responsible for all that is blocked.

The solution is to do this blocking operation in an own thread. Roughly like
Code:
Thread thread = new Thread(new Runnable()
{
    public void run()
    {
        // Your "red" block here
    }
});
thread.start();

You might have to think about how the results which are read from the socket will then be processed further. For example, if the result should be displayed in a JLabel, THIS should be done on the Event Dispatch Thread again. You might also want to have a look at the "SwingWorker" class, which is intended for long-lasting Operations that should be started from a Swing GUI, but in the simplest case, creating a new Thread will be sufficient.
 

Neue Themen


Zurück
Oben