Output stream to GUI text box

I'm trying to get the output to a TextField in a GUI, but all I get is thread information. This is just a small collection of the complete code, but the full version has the same problem. The full version has 5 different threads running simultaneously. Any help or advice would be appreciated.

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

      

This is the main thing.

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

      

+3


source to share


1 answer


You write o1 once and get the default toString()

from the stream, so I'm not surprised you see anything but junk. My suggestion:

  • Build SwingWorker<Void, String>

    inside your GUI.
  • Run your long code from SwingWorker doInBackground
  • Publish any strings the GUI requires by calling publish(...)

    , passing in a string.
  • Display them in a GUI using the SwingWorker process(...)

    .
  • Don't use static variable as kludge for cross-thread communication. This is a very easily destructible non-solution.
  • Avoid calling setBounds()

    in Swing GUI. Although Zero Layouts setBounds()

    may seem like the easiest and best way to create complex GUIs to Swing newbies, the more Swing GUIs you create, the more difficult you will encounter when using them. They will not resize your components when the GUI is resized, they are a queen witch for enhancement or support, they completely fail when placed in scrollpanes, they look awful awful when viewed on all platforms or screen resolutions other than the original. Instead learn and use layout managers.
  • Take a look: Tutorial: Concurrency in Swing .



eg. something like

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

      

+3


source







All Articles