Reputation: 139
I have a label that isn't updating in the same instance of the GUI. If I click the jButton that should update the value on a jLabel ("testLabel" from block of code), I have to run the java program again to see the change appear. How can I get it to appear on button click in the same instance? I know about invokelater and I've been playing with it trying to get it to update in real time, but with no luck. I've been stuck on this for awhile now so any help is appreciated. With the block of code listed below I still have to run a new instance of the GUI to get the value to update.
Related code:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
// testLabel.setText(CN);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
try (BufferedReader br = new BufferedReader(new FileReader(
"resultofbatch.txt"))) {
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);
}
Full Class Code http://pastebin.com/havyqMxP
Computer Query Class (Small Class) http://pastebin.com/Q89BCjya
Upvotes: 0
Views: 157
Reputation: 3978
As promised... here is a simple example of fetching an URL content using swing worker to decouple the task of getting the contents (the long running task) from the task that update the swing components. This will show an example of how you should approach this issue...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
/* FrameDemo.java requires no other files. */
public class MainWindow extends JFrame {
private static final Logger LOOGER = Logger.getLogger(MainWindow.class.getName());
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private JLabel statusLabel = new JLabel("Status");
private JButton actionButton = new JButton("Push me");
public MainWindow() {
super("FrameDemo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
statusLabel = new JLabel("Status");
actionButton = new JButton("Push me");
statusLabel.setPreferredSize(new Dimension(400, 50));
actionButton.setPreferredSize(new Dimension(100, 50));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(statusLabel, BorderLayout.NORTH);
getContentPane().add(actionButton, BorderLayout.CENTER);
actionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// THIS METHOD IS INVOKED WITHIN THE EVENT DISPATCH THREAD!!.. SO IS CRUCIAL TO NOT PERFORM
// HERE LONG TIME RUNNING TASKS...
actionButton.setEnabled(false); // let's disable this button, in order to avoid invoking
// multiple times the same task and messing up the entire app...
UrlFechterSwingWorker urlFechterSwingWorker = new UrlFechterSwingWorker();
urlFechterSwingWorker.execute();
}
});
}
public void display() {
pack();
setVisible(true);
}
private class UrlFechterSwingWorker extends SwingWorker<String, String> {
@Override
public String doInBackground() { // this method is executed under a worker thread
BufferedReader in;
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("http://www.stackoverflow.com");
in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while (line != null) {
sb.append(line);
publish(line); // publish partial results....
line = in.readLine();
}
in.close();
} catch (Exception e) {
LOOGER.log(Level.SEVERE, "", e);
}
return sb.toString();
}
@Override
protected void process(List<String> readedLines) { // this method in the Event dispatch Thread
// do what you want to do with the readedLines....
statusLabel.setText("The doInBackground read... " + readedLines.size() + " lines");
}
@Override
public void done() { // this method in the Event dispatch Thread
// do what you want when the process finish
actionButton.setEnabled(true); // well.. at least i would like to enable the button again...
}
}
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.display();
}
}
Here are more tips:
After you understand (more or less) how things are working in the above example.. you will have to implement a proper doInBackground
method that perform all the LDAP stuff, for this you will have to make your mind to conceive a way of informing the progress to a end user... i mean, look my example, is very poor regarding progress advance.. all the thing that i am stating is that, we read "a number of lines" from a given url. You should think what is the best way to inform progress regarding your task.. there is no template for this except the understanding of the underlying domain model.
Have in mind that swing workers has two ways to inform about the progress.
publish
and process
method in conjunction. (Like the example above)doInBackground
, and attach a PropertyChangeListener
to the swing worker. This propertyChangeListener object has a method whose signature is public void propertyChange(PropertyChangeEvent evt)
(a little more complex, on my point of view..)Patience and good luck!
Upvotes: 2