【问题标题】:Thread output to GUI Text Field线程输出到 GUI 文本字段
【发布时间】:2015-07-24 03:11:05
【问题描述】:

我试图在 GUI 的 TextField 中输出,但我得到的只是线程信息。这只是完整代码中的一小部分,但完整版本有同样的问题。完整版有 5 个不同的线程同时运行。任何帮助或建议将不胜感激。

public class O21 implements Runnable {
@Override
public void run() {

    try {
        Scanner O1 = new Scanner(new File("O21.txt"));
        O1.useDelimiter(",");
        while (O1.hasNext()) {
            String a = O1.next();
            int aa = Integer.parseInt(a);
            Thread.sleep(500); // Time delay to sync output
            if (a.trim().isEmpty()) {
                continue;
            }
            System.out.println(a);
        }
    } catch (Exception f) {
        f.printStackTrace();
    }}}

这是主要的。

public class Window {
    private JFrame frmTest;
    private JTextField txtTank1;
    private JTextField textField_4;
    static String o1;

/**
 * Launch the application.
 */
public static void main(String[] args) throws Exception {

    Thread a = new Thread(new O21());
    a.start();

    o1= a.toString();

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Window window = new Window();
                window.frmTest.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
}

/**
 * Create the application.
 */
public Window() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frmTest = new JFrame();
    frmTest.setAlwaysOnTop(true);
    frmTest.setResizable(false);
    frmTest.setBounds(100, 100, 350, 400);
    frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmTest.getContentPane().setLayout(null);

    txtTank1 = new JTextField();
    txtTank1.setText("Tank1");
    txtTank1.setFont(new Font("Tahoma", Font.PLAIN, 20));
    txtTank1.setEditable(false);
    txtTank1.setColumns(10);
    txtTank1.setBounds(10, 60, 150, 50);
    frmTest.getContentPane().add(txtTank1);

    textField_4 = new JTextField();
    textField_4.setEditable(true);
    textField_4.setText(o1);
    textField_4.setFont(new Font("Tahoma", Font.PLAIN, 20));
    textField_4.setColumns(10);
    textField_4.setBounds(170, 60, 150, 50);
    frmTest.getContentPane().add(textField_4);
}}

【问题讨论】:

  • 请查看编辑以回答,包括代码。

标签: java multithreading swing user-interface


【解决方案1】:

您正在向 o1 写入一次,并且只从线程中获取默认的 toString(),所以我对您只看到垃圾内容并不感到惊讶。我的建议:

  • 在您的 GUI 中创建 SwingWorker<Void, String>
  • 在 SwingWorker 的 doInBackground 中运行长时间运行的代码
  • 通过调用publish(...) 并传入字符串来发布GUI 需要的任何字符串。
  • 使用 SwingWorker 的 process(...) 方法在 GUI 中显示它们。
  • 不要使用静态变量作为线程间通信的工具。这是一个非常容易破解的非解决方案。
  • 避免在 Swing GUI 中调用 setBounds()。虽然空布局和setBounds() 对于 Swing 新手来说似乎是创建复杂 GUI 的最简单和最好的方法,但创建的 Swing GUI 越多,使用它们时遇到的困难就越严重。当 GUI 调整大小时,它们不会调整您的组件大小,它们是增强或维护的皇家女巫,放置在滚动窗格中时它们完全失败,在与原始不同的所有平台或屏幕分辨率上查看时它们看起来很糟糕.而是了解和使用布局管理器。
  • 看看:Tutorial: Concurrency in Swing

例如比如,

import java.io.File;
import java.util.List;
import java.util.Scanner;

import javax.swing.*;

public class SwingThreadingEg extends JPanel implements MyAppendable {
   private JTextArea area = new JTextArea(30, 50);

   public SwingThreadingEg() {
      JScrollPane scrollPane = new JScrollPane(area);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      add(scrollPane);
   }

   @Override
   public void append(String text) {
      area.append(text);
   }

   private static void createAndShowGui() {
      SwingThreadingEg mainPanel = new SwingThreadingEg();
      MyWorker myWorker = new MyWorker(mainPanel);
      // add a Prop Change listener here to listen for 
      // DONE state then call get() on myWorker
      myWorker.execute();

      JFrame frame = new JFrame("SwingThreadingEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MyWorker extends SwingWorker<Void, String> {
   private MyAppendable myAppendable;

   public MyWorker(MyAppendable myAppendable) {
      this.myAppendable = myAppendable;
   }

   @Override
   protected Void doInBackground() throws Exception {
      try (Scanner O1 = new Scanner(new File("O21.txt"))) {

         O1.useDelimiter(",");
         while (O1.hasNext()) {
            String a = O1.next();
            int aa = Integer.parseInt(a);
            Thread.sleep(500); // Time delay to sync output
            if (a.trim().isEmpty()) {
               continue;
            }
            System.out.println(a);
            publish(a);
         }
      } catch (Exception f) {
         f.printStackTrace();
      }
      return null;
   }

   @Override
   protected void process(List<String> chunks) {
      for (String text : chunks) {
         myAppendable.append(text + "\n");
      }
   }
}

interface MyAppendable {
   public void append(String text);
}

【讨论】:

  • 为什么 OP 的 window.frmTest.setVisible(true); 不会抛出 NPE
  • @PM77-1:不知道。一看到他在一个线程上调用toString(),我就放弃了详细查看他的代码!
  • 谢谢,这正是我所需要的。我无法正确输出字符串。并且 window.frmTest.setVisible(true); 是由窗口构建器自动生成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2015-07-18
相关资源
最近更新 更多