2012-03-13 28 views
-2

我想要一個完全可以工作的JTextArea而不是控制檯但我不知道該怎麼做!在JTextArea而不是控制檯上顯示數據

謝謝

+0

我仍然不能相信-6這種顯着的問題! :D – SAbbasizadeh 2013-08-23 07:07:42

+2

很可能是因爲你的問題沒有顯示出任何努力來解決你自己的問題。 – 2013-08-23 07:31:23

回答

18

該問題的解決方案是System.{in,out,err}重定向到一個JTextArea


  • System.out開始它非常直截了當地將其重定向到使用System.setOut方法您JTextArea組件。在下面的示例中,我使用管道和SwingWorker完成了這個工作,但這些都是讓輸出變得更簡單的擺動組件。

  • 模擬System.in是類似的,您需要使用System.setIn將擊鍵重定向到System.in。再次,在下面的例子中,我使用管道來獲得更好的界面。我也緩衝線(就像一個「正常」的控制檯會這樣做),直到你輸入。 (注意,例如箭頭鍵將無法正常工作,但它不應該是很多工作得到它也被處理/忽略)。


的截圖下面的文字製作

screenshot

public static JTextArea console(final InputStream out, final PrintWriter in) { 
    final JTextArea area = new JTextArea(); 

    // handle "System.out" 
    new SwingWorker<Void, String>() { 
     @Override protected Void doInBackground() throws Exception { 
      Scanner s = new Scanner(out); 
      while (s.hasNextLine()) publish(s.nextLine() + "\n"); 
      return null; 
     } 
     @Override protected void process(List<String> chunks) { 
      for (String line : chunks) area.append(line); 
     } 
    }.execute(); 

    // handle "System.in" 
    area.addKeyListener(new KeyAdapter() { 
     private StringBuffer line = new StringBuffer(); 
     @Override public void keyTyped(KeyEvent e) { 
      char c = e.getKeyChar(); 
      if (c == KeyEvent.VK_ENTER) { 
       in.println(line); 
       line.setLength(0); 
      } else if (c == KeyEvent.VK_BACK_SPACE) { 
       line.setLength(line.length() - 1); 
      } else if (!Character.isISOControl(c)) { 
       line.append(e.getKeyChar()); 
      } 
     } 
    }); 

    return area; 
} 
:由一個號碼的呼叫的「正常」 System.out.print..方法的,然後用 Scanner等待輸入上

和示例main方法:

public static void main(String[] args) throws IOException { 

    // 1. create the pipes 
    PipedInputStream inPipe = new PipedInputStream(); 
    PipedInputStream outPipe = new PipedInputStream(); 

    // 2. set the System.in and System.out streams 
    System.setIn(inPipe); 
    System.setOut(new PrintStream(new PipedOutputStream(outPipe), true)); 

    PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true); 

    // 3. create the gui 
    JFrame frame = new JFrame("\"Console\""); 
    frame.add(console(outPipe, inWriter)); 
    frame.setSize(400, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

    // 4. write some output (to JTextArea) 
    System.out.println("Hello World!"); 
    System.out.println("Test"); 
    System.out.println("Test"); 
    System.out.println("Test"); 

    // 5. get some input (from JTextArea) 
    Scanner s = new Scanner(System.in); 
    System.out.printf("got from input: \"%s\"%n", s.nextLine()); 
} 
1
+0

我是新來的java,我做的只是簡單地複製教程代碼,並將其粘貼到我的java類,並希望它運行。那麼給出的代碼不是這樣工作的。 :) – 2014-05-21 07:03:29

相關問題