【发布时间】:2015-07-04 13:44:44
【问题描述】:
我正在尝试让一个线程在单击按钮时为 swing 应用程序运行,但该值没有更新。 它应该获取我正在搜索的计算机名称,但为了更新值,我必须启动一个新的 GUI 实例。 我创建了一个线程,但由于某种原因它不起作用。任何帮助表示赞赏。
(t.start 在代码块的末尾)
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread("my non EDT thread") {
public void run() {
//my work
testLabel.setText(CN);
}
};
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();
t.start();
}
});
更新
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
我把方法放在这里
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
【问题讨论】:
-
所有 GUI 更新都应在 EDT 上完成。
-
我以前听过这个,但我不是很明白。你有没有机会给我一个我应该做什么的工作示例?
-
“你有没有机会给我一个工作的例子..” 你有没有机会意识到 SO 不是一个代码生成机器,并实际投入一些靠自己努力?碰巧,我有一个围绕这些部分的示例,它使用 Swing
Timer定期建立SwingWorker并重复执行长时间运行的任务。搜索一下,你可能会找到它。
标签: java swing concurrency jlabel event-dispatch-thread