Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 控制台输出到WindowBuilder GUI_Java_Eclipse_Swing_Windowbuilder - Fatal编程技术网

Java 控制台输出到WindowBuilder GUI

Java 控制台输出到WindowBuilder GUI,java,eclipse,swing,windowbuilder,Java,Eclipse,Swing,Windowbuilder,我目前有一个程序,可以在“System.out.println()”语句的不同行中将文本行打印到屏幕上。我不熟悉Java、Eclipse和WindowBuilder 我现在正在为这个程序添加一个GUI。我能够创建带有按钮的GUI,这些按钮工作正常。我的问题是,我希望将所有打印到eclipse控制台(或命令行)的内容实时打印到GUI中的文本框中。我怎样才能轻松做到这一点 package Onur; import java.awt.BorderLayout; public class Beha

我目前有一个程序,可以在“System.out.println()”语句的不同行中将文本行打印到屏幕上。我不熟悉Java、Eclipse和WindowBuilder

我现在正在为这个程序添加一个GUI。我能够创建带有按钮的GUI,这些按钮工作正常。我的问题是,我希望将所有打印到eclipse控制台(或命令行)的内容实时打印到GUI中的文本框中。我怎样才能轻松做到这一点

package Onur;


import java.awt.BorderLayout;

public class BehaSendDFGUI extends JFrame {

    private BehaviourSendWithDF1 myAgent; // Reference to the agent class
    private JPanel contentPane;
    private JDesktopPane desktopPane;
    private JButton btnMessage;
    private JButton btnMessage_1;
    private JButton btnMessage_2;
    private JButton btnMessage_3;
    private JTextArea textArea = new JTextArea();

    public void setAgent(BehaviourSendWithDF1 a) {
        myAgent = a; // provide the value of the reference of BehaviourSendWithDF1 class here

    }

    private void updateTextArea(final String text) {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                textArea.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));
        }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BehaSendDFGUI frame = new BehaSendDFGUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public BehaSendDFGUI() {


        setTitle("Behaviour Sender");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 523, 398);

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        JMenuItem mntmExit = new JMenuItem("Exit");
        mnFile.add(mntmExit);

        JMenu mnAbout = new JMenu("About");
        menuBar.add(mnAbout);

        JMenuItem mntmAboutThisGui = new JMenuItem("About This GUI");
        mnAbout.add(mntmAboutThisGui);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        contentPane.add(toolBar, BorderLayout.CENTER);

        desktopPane = new JDesktopPane();
        toolBar.add(desktopPane);

        btnMessage = new JButton("Send Message 1");
        btnMessage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                BehaviourSendWithDF1.STEP = "1";
                System.out.println("Button Pressed => STEP = " + BehaviourSendWithDF1.STEP );
                myAgent.behaSend();             
            }

        });
        btnMessage.setBounds(10, 11, 111, 23);
        desktopPane.add(btnMessage);

        btnMessage_1 = new JButton("Send Message 2");
        btnMessage_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                BehaviourSendWithDF1.STEP = "2";
                System.out.println("Button Pressed => STEP = " + BehaviourSendWithDF1.STEP );
                myAgent.behaSend(); 
            }
        });
        btnMessage_1.setBounds(131, 11, 111, 23);
        desktopPane.add(btnMessage_1);

        btnMessage_2 = new JButton("Send Message 3");
        btnMessage_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BehaviourSendWithDF1.STEP = "3";
                System.out.println("Button Pressed => STEP = " + BehaviourSendWithDF1.STEP );
                myAgent.behaSend(); 
            }
        });
        btnMessage_2.setBounds(252, 11, 111, 23);
        desktopPane.add(btnMessage_2);

        btnMessage_3 = new JButton("Send Message 4");
        btnMessage_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BehaviourSendWithDF1.STEP = "4";
                System.out.println("Button Pressed => STEP = " + BehaviourSendWithDF1.STEP );
                myAgent.behaSend(); 
            }
        });
        btnMessage_3.setBounds(373, 11, 111, 23);
        desktopPane.add(btnMessage_3);

        JButton btnExitGui = new JButton("Exit GUI");
        btnExitGui.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        btnExitGui.setBounds(189, 293, 130, 23);
        desktopPane.add(btnExitGui);

        JTextPane txtpnConsoleOutput = new JTextPane();
        txtpnConsoleOutput.setText("Console Output:");
        txtpnConsoleOutput.setBounds(10, 45, 101, 20);
        desktopPane.add(txtpnConsoleOutput);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 76, 475, 206);
        desktopPane.add(scrollPane);
        scrollPane.setViewportView(textArea);

        redirectSystemStreams();

    }
}
我在NetBeans上见过此解决方案,但无法将其应用于WindowBuilder:

提前谢谢

编辑:在问题中编辑代码的工作版本。谢谢你的帮助。

你的问题包括

  • 您试图使用不存在的变量textPane和
  • 您的程序没有可以显示文本的文本组件。我建议您至少添加一个JTextArea,以便将输出重定向到它。如果你愿意,可以叫它textPane,但不管你叫它什么,你至少需要有一个可以显示多行文本的东西
  • 同样,您提供的链接中描述的一般技术是正确的——您需要将System.out和System.err重定向到您创建的输出流
  • 但是您必须注意只在Swing事件线程上更新Swing组件,因此使用
    SwingUtilities.invokeLater(new Runnable(){…})
  • 因此,正确使用本文的建议将起作用。所以坚持下去
  • 再次阅读Swing教程,并将windows builder代码生成器放在一边。代码生成器可以用来节省您的时间,但是如果您在对Swing库有很好的了解之前就使用它们,那么在您需要最基本的GUI和行为之外的任何东西时,您都可能会遇到大问题

    编辑
    您似乎试图调用JTextField上的
    append(…)
    ,此类不允许该消息。我建议

    • 您可以大大简化类,使其只有最基本的GUI来演示System.out和err的重定向,以及
    • 再次使用JTextArea,而不是JTextField
    编辑2
    你问:

    我无法解决“textArea.append(text);”问题作用域错误:无法解析textArea

    请注意声明textArea变量的位置。因为它不是在类中声明的,而是在方法或构造函数中声明的,所以它在类的其他地方不可见。解决方案是在类中声明它,而不是在其他地方

    编辑3
    比如说,

    import java.awt.event.ActionEvent;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintStream;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class RedirectOut extends JPanel {
       private static final int BUTTON_COUNT = 4;
       private JTextArea textArea = new JTextArea(20, 20);
       private SomeAgent myAgent;
    
       public RedirectOut() {
          redirectSystemStreams();
    
          setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    
          for (int i = 0; i < BUTTON_COUNT; i++) {
             final int count = i + 1;
             JButton button = new JButton(new AbstractAction("Send Message " + count){
                @Override
                public void actionPerformed(ActionEvent e) {
                   myAgent.setStep(String.valueOf(count));
                   System.out.println("Button Pressed => STEP = "
                         + myAgent.getStep());
                   myAgent.behaSend();
                }
             });
             JPanel btnPanel = new JPanel();
             btnPanel.add(button);
             add(btnPanel);
          }
          add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
       }
    
       public void setAgent(SomeAgent agent) {
          this.myAgent = agent;
       }
    
       public void updateTextArea(final String text) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                textArea.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));
       }
    
       private static void createAndShowGui() {
          RedirectOut redirectOut = new RedirectOut();
          redirectOut.setAgent(new SomeAgent());
    
          JFrame frame = new JFrame("RedirectOut");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(redirectOut);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    导入java.awt.event.ActionEvent;
    导入java.io.IOException;
    导入java.io.OutputStream;
    导入java.io.PrintStream;
    导入javax.swing.*;
    @抑制警告(“串行”)
    公共类重定向扩展JPanel{
    私有静态最终整数按钮计数=4;
    私有JTextArea textArea=新JTextArea(20,20);
    私人代理人;
    公共重定向输出(){
    重定向系统流();
    setLayout(新的BoxLayout(这是BoxLayout.PAGE_轴));
    对于(int i=0;i<按钮计数;i++){
    最终整数计数=i+1;
    JButton按钮=新JButton(新抽象操作(“发送消息”+计数){
    @凌驾
    已执行的公共无效操作(操作事件e){
    myAgent.setStep(String.valueOf(count));
    System.out.println(“按下的按钮=>STEP=”
    +myAgent.getStep());
    myAgent.behaSend();
    }
    });
    JPanel btnPanel=新的JPanel();
    btnPanel.add(按钮);
    添加(btnPanel);
    }
    添加(新的JScrollPane(文本区域,JScrollPane.VERTICAL\u滚动条\u始终,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }
    公共代理(某些代理){
    this.myAgent=agent;
    }
    public void updateTextArea(最终字符串文本){
    SwingUtilities.invokeLater(新的Runnable(){
    公开募捐{
    textArea.append(文本);
    }
    });
    }
    私有无效重定向SystemStreams(){
    OutputStream out=新的OutputStream(){
    @凌驾
    公共无效写入(int b)引发IOException{
    updateTextArea(String.valueOf((char)b));
    }
    @凌驾
    公共无效写入(字节[]b,int off,int len)引发IOException{
    updateTextArea(新字符串(b,off,len));
    }
    @凌驾
    公共无效写入(字节[]b)引发IOException{
    写入(b,0,b.长度);
    }
    };
    系统放样(新打印流(输出,真实));
    System.setErr(新打印流(out,true));
    }
    私有静态void createAndShowGui(){
    RedirectOut RedirectOut=新的RedirectOut();
    setAgent(newsomeagent());
    JFrame=新JFrame(“重定向输出”);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(重定向出);
    frame.pack();
    frame.setLocationByPlatform(真);
    frame.setVisible(true);
    }
    公共静态void main(字符串[]args){
    SwingUtilities.invokeLater(新的Runnable(){
    公开募捐{
    createAndShowGui();
    }
    });
    }
    }
    
    重定向System.out和System.err的解决方案是相同的,这与NetBeans、WindowsBuilder或任何其他Swing windows building实用程序完全无关,而与Swing有关。如果这个解决方案对您不起作用,那么您需要告诉我们更多,包括它不起作用的确切方式或原因;但是有很多我无法解决的错误。当然你不能这样做。永远不要盲目地复制和粘贴代码,尤其是您不理解的代码。相反,学习代码试图做什么,并使用这些概念编写自己的代码。你的问题需要更多地围绕着什么展开