I have a jtextfield where I input part of a computer name in and when I click search, it gives me the full computer name. My issue is that the full computer name is supposed to output to a jLabel, but it only outputs if I run another instance of the GUI. I know I have to use Swingworker to get it to output on (Search Button) button click, but it never outputs within the same instance. Any help is appreciated.
I don't want to miss anything out of the code I'm listing so here's the full class I'm trying to use SwingWorker with. The doInBackground() method is at the bottom of the class. The jLabel I'm trying to output the computer name to is called "testLabel"
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=",-1)[1].split(",",-1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
SwingUtilities.invokeLater(updateCN());
Code at bottom of class
private Runnable updateCN() {
testLabel.setText("Test afterwards");
return null;
Any updates to the GUI should be performed in the Event Dispatching Thread. And
SwingWorker.doInBackground()
performs a task in a background thread (non EDT). So you seem to have mixed it up.To fix it, always perform your setText in a EDT thread by calling
SwingUtilities.invokeLater()
orSwingUtilities.invokeAndWait()
. If you want to do a long running process which doesn't update the GUI from EDT, then useSwingWorker.doInBackground()
.Also, the
doInBackground()
method is called only when you invokeSwingWorker.execute()
which you don't seem to have done anywhere in your code.