我正在尝试在按钮点击时为一个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;
答案 0 :(得分:1)
请注意Swing Thread https://docs.oracle.com/javase/tutorial/uiswin/concurrency/
看看这里: http://www.javamex.com/tutorials/threads/invokelater.shtml
您必须使用Method将JLabel更新方法调用入队 SwingUtilities.invokeLater(???)。 以下示例
我认为这与.batch文件调用有关。看看这里:How do I run a batch file from my Java Application? Runnable task = new UpdateJob(" Query:" + i); SwingUtilities.invokeLater(任务);
让它更容易理解。
Swing管理一个Thread内的所有draw-Operations。 它提供了一个队列。如果从该队列外部调用方法,则行为完全不可预测.. NullPointer ... RuntimeExc .... 但是如果你调用SwingUtilities.invokeLater(...),你的方法将被排入Swing-Queue并尽快调用!
由于评论更新:
检查你的主线程(GUI) 检查你的线程。 当子线程(例如ActionListener)想要调用JLabel :: setText时 它必须使用方法SwingUtils :: InvokeLater(" ...");
这意味着必须在不直接属于主线程的所有线程中调用invokeLater()
。
由于问题而更新
在我的观点中,您当前的代码根本不需要SwingUtilities.invok .. 您是否更改了分配给您的代码?