2013-04-02 4 views
0

현재 다른 줄의 'System.out.println()'문에서 화면에 텍스트 줄을 인쇄하는 프로그램이 있습니다. Java, Eclipse 및 WindowBuilder를 처음 사용합니다.콘솔 출력을 WindowBuilder GUI

이제이 프로그램에 GUI를 추가하고 있습니다. OK 버튼을 사용하여 GUI를 만들 수있었습니다. 내 문제는 이클립스의 콘솔 (또는 명령 줄)에 인쇄되는 모든 것을 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(); 

    } 
} 

내가 넷빈즈에이 솔루션을 보았다하지만 WindowBuilder을 위해 그것을 적용 할 수 있습니다 : 사전에

http://unserializableone.blogspot.com/2009/01/redirecting-systemout-and-systemerr-to.html

감사합니다.

편집 : 코드의 작업 버전은 질문에서 편집됩니다. 모든 도움에 감사드립니다.

+0

용액은은 System.out 및 System.err에 * 리디렉션 *이 동일하고,이 넷빈즈 또는 WindowsBuilder 또는와는 전혀 무관 다른 스윙 창 구축 유틸리티 및 스윙과 관련된 모든 것. 그 해결책이 당신을 위해 작동하지 않는 경우에, 정확하게 작동하지 않는 방법 또는 왜 그것을 포함하여 저희에게 더 많은 것을 말해야합니다. –

+0

코드를 복사하여 Eclipse에 붙여 넣으려고합니다. 그러나 내가 풀 수없는 많은 에로스를 얻는다. –

+0

물론 당신은 그렇게 할 수 없습니다. 코드를 맹목적으로 복사하여 붙여 넣지 마십시오. 특히 이해하지 못하는 코드는 특히 그렇습니다. 대신 코드가 수행하려고하는 것을 배우고 자신의 코드를 작성하는 개념을 사용하십시오. 귀하의 질문은 귀하가 이해하지 못하는 부분에 대해 더 많은 관심을 기울여야합니다. 그렇지 않으면이 질문이 도움이되지 않습니다. –

답변

1

귀하의 문제는 당신이 textPane 존재하지 않는 변수를 사용하려는, 그리고

  • 이 프로그램은 텍스트를 표시 할 수있는 텍스트 구성 요소가없는

    1. 있습니다. 최소한 JTextArea를 추가하여 출력을 리디렉션 할 수 있도록 제안하십시오. 원한다면 textPane이라고 부르지 만 무엇이든지 호출하면 적어도 의 텍스트를 여러 줄 표시 할 수 있어야합니다.
    2. 제공된 링크에서 설명하는 일반적인 기술은 정확합니다. System.out 및 System.err을 생성물의 OutputStream으로 리디렉션해야합니다.
    3. 따라서 Swing 이벤트 스레드에서만 Swing 구성 요소를 업데이트해야합니다. 따라서 SwingUtilities.invokeLater(new Runnable() {...})을 사용하십시오.
    4. 올바르게 사용되었으므로 문서의 권장 사항 이됩니다. 그러니 계속 지켜라.

    다시 스윙 튜토리얼을 읽고 창 빌더 코드 생성기를 따로 보관하십시오. 코드 생성기를 사용하면 시간을 절약 할 수 있지만 Swing 라이브러리에 대해 잘 이해하기 전에이 코드를 사용하면 가장 기본적인 GUI 및 동작 이외의 다른 것이 필요할 때마다 큰 문제가 발생할 수 있습니다.

    편집
    당신은 표시는 JTextField를에 append(...)를 호출하려고합니다,이 클래스는 메시지를 허용하지 않습니다. 나는 JTextArea에,하지 JTextField로를 사용하여 다시

    가 잘못을 System.out에의 리디렉션 및을 입증하는 가장 기본적인 GUI를 가지고 있도록 크게 클래스를 단순화
    • 을 제안한다.

    편집 2
    당신은 질문 : 당신이 텍스트 영역의 변수를 선언

    I couldn't solve the 'textArea.append(text);' scope error: textArea cannot be resolved.

    참고. 클래스에서 선언되지 않고 메서드 또는 생성자로 선언되었으므로 클래스의 다른 곳에 표시되지 않습니다. 해결책은 다른 곳에서가 아니라 클래스에서 선언하는 것입니다. 예를 들어 편집 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(); 
         } 
         }); 
        } 
    } 
    
  • +0

    나는 1과 2를 얻었고 고쳤다. 네가 의미하는 바를 얻지 못한다. 나는 범위 에러를 수정하고 텍스트 영역을 생성 한 후 코드에서 redirectSystemStreams()를 호출하려고 시도했다. 컴파일 오류는 없지만 GUI를 실행하면 아무 것도 인쇄되지 않습니다. –

    +0

    @OnurDogu : 편집 참조 –

    +0

    또한 왜 JDesktopPane을 사용하고 있습니까? –

    관련 문제