将控制台输出重定向到 GUI [英] Redirecting console output to GUI

查看:55
本文介绍了将控制台输出重定向到 GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我借用了在 stackoverflow 上找到的一个设计,将控制台输出重定向到 GUI.它工作正常,直到我开始从我的程序中的文本文件中读取.现在,当我使用 GUI 运行程序时,不会显示任何输出,并且 GUI 会冻结,然后最终自行关闭.这是我的 GUI 代码的精简版:

I borrowed a design that I found on stackoverflow to redirect console output to a GUI. It worked fine until I started reading from text files in my program. Now when I run the program using the GUI no output is displayed and the GUI freezes and then closes on its own eventually. Here is a slimmed down version of my GUI code:

public class GreenhouseControlsGUI {
    public static class MyGui extends JFrame implements ActionListener {

      // Start button 
      JButton Start = new JButton("Start");

      /..................................../

      /**
       * The constructor.
       */ 
     public MyGui(){     
        super("Greenhouse Controls");

            /............................../

        bottomPanel.setLayout(new FlowLayout());
        bottomPanel.add(Start);

            /............................../

        getContentPane().add(holdAll, BorderLayout.CENTER);

        Start.addActionListener(this);

            /............................../

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
     }

    public void actionPerformed(ActionEvent e){

        if (e.getSource() == Start)
            GreenhouseControls.startMeUp(); // Start program...

            /............................../
        }

    public static void main(String[] args){

        MyGui myApplication = new MyGui();

        // redirect output to GUI
        myApplication.redirectSystemStreams();

        // Specify where will it appear on the screen:
        myApplication.setLocation(10, 10);
        myApplication.setSize(500, 300);

        // Show it!
        myApplication.setVisible(true);
      } 

      private void updateTextArea(final String text) {
            SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                myText.append(text);
              }
            });
          }

      private void redirectSystemStreams() {

          OutputStream out = new OutputStream() {

              @Override
              public void write(int b) throws IOException {
                updateTextArea(String.valueOf((char) b));
              }

              @Override
              public void write(byte[] b, int off, int len) throws IOException {
                updateTextArea(new String(b, off, len));
              }

              @Override
              public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
              }
            };

            System.setOut(new PrintStream(out, true));
            System.setErr(new PrintStream(out, true));
          }
    }
}

我很确定我的问题始于从下面代码中的文件名"路径读取,因为当我将文件名"变量声明注释掉时我没有这个问题.我认为将控制台输出重定向到我的 GUI 的方法只是重定向输出......为什么当我从文件中读取时它会搞砸一切?我是编程新手,我可能忽略了一些明显的东西,但我无法弄清楚.

I'm pretty sure my problem starts with reading from the 'filename' path in the code below because I don't have this problem when I comment the 'filename' variable declaration out. I thought the methods to redirect console output to my GUI were only redirecting output.... Why is it screwing everything up when I read from a file? I am new to programming and I have probably overlooked something obvious, but I can't figure it out.

这是在 GUI 类中调用的静态 startMeUp() 方法:

Here is the static startMeUp() method invoked inside the GUI class:

public static void startMeUp() {
        try {
            String option   = "-f";                    // (-f) to start program or (-d) to restore program
            filename = "src/greenhouse/examples3.txt"; // read file from here
            dumpFile = "dump.out";                     // restore program from here

            // if option is invalid invoke corresponding print statement
            if ( !(option.equals("-f")) && !(option.equals("-d")) ) {
               System.out.println("Invalid option");
                printUsage();
            }

            GreenhouseControls gc = new GreenhouseControls(); // Create GreenhouseControls object 
            Restart restart = new Restart(0,filename, gc);    // Create Restart object
            Restore restore = new Restore(0,dumpFile);        // Create Restore object

            // if the option value is -f ... 
            if (option.equals("-f"))  {
                gc.addEvent(restart);      // add new Restart object to addEvent() 
            }
            gc.run();                                   

            // if the option value is -d ... 
            if (option.equals("-d"))  {
                gc.addEvent(restore);     // add new Restore object to addEvent()
            }
            gc.run();

            }catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of parameters");
            printUsage();
        }
    }

推荐答案

您需要在新线程中调用 startMeUp,因为您的控制台程序正在阻塞事件调度线程.像这样:

You need to invoke startMeUp in a new thread, because your console program is blocking the event dispatch thread. Like this:

new Thread () {
  @Override public void run () {
    GreenhouseControls.startMeUp();
  }
}.start();

而不仅仅是

GreenhouseControls.startMeUp();

这篇关于将控制台输出重定向到 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆