标签不在GUI的同一实例中更新

时间:2015-07-03 12:59:07

标签: java swing concurrency swingworker

我有一个标签,不会在GUI的同一个实例中更新。 如果我单击应该更新jLabel(" testLabel"来自代码块)的值的jButton,我必须再次运行java程序以查看更改。如何让它出现在同一个实例中的按钮单击上? 我知道invokelater,我一直在玩它试图让它实时更新,但没有运气。我现在已经坚持了一段时间,所以任何帮助都会受到赞赏。 使用下面列出的代码块,我仍然需要运行GUI的新实例来获取要更新的值。

相关代码:

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);
            }

完整的班级代码 http://pastebin.com/havyqMxP

计算机查询类(小班) http://pastebin.com/Q89BCjya

1 个答案:

答案 0 :(得分:2)

正如所承诺的......这是一个使用swing worker获取URL内容的简单示例,用于将获取内容(长时间运行的任务)的任务与更新swing组件的任务分离。这将显示您应如何处理此问题的示例......

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();
  }
}

以下是更多提示:

  1. 在您(或多或少)了解上述示例中的工作原理之后......您必须实现一个执行所有LDAP内容的正确doInBackground方法,为此您必须让你的思想构思一种向最终用户通报进展的方式......我的意思是,看看我的例子,对于进步的进展是非常糟糕的...我所说的所有事情都是,我们读到了“一些行“来自给定的网址。您应该考虑什么是告知有关您的任务进度的最佳方式..除了对基础域模型的理解之外,没有此模板。

  2. 请记住,摇摆工人有两种方式来告知进展情况。

    • 一个人正在使用publishprocess方法。 (如上例所示)
    • 其他方法是修改方法doInBackground内的内部属性(进度和状态),并将PropertyChangeListener附加到swing工作者。这个propertyChangeListener对象有一个签名为public void propertyChange(PropertyChangeEvent evt)的方法(在我的观点上稍微复杂一些......)
  3. 耐心和好运!