2016-05-16 61 views
0

我想從Java控制檯可視化我的消息到jpanel或jTextArea,我創建了2個類:第一個包含來自perl腳本的輸出消息「hello world! 「我想從其他類我的JTextArea看到這則消息時,我從第二類單擊一個JButton - >這是我的第一類我的腳本從java控制檯重新指定輸出消息到jTextArea或jLabel

package escudo; 
import java.io.IOException; 
import java.io.InputStream; 
public class MediocreExecJavac { 
    public static void main(String[] args) { 
     try { 
      // Run the process 
      Process p = Runtime.getRuntime().exec("perl script\\hello.pl"); 
      // Get the input stream 
      InputStream is = p.getInputStream(); 
      // Read script execution results 
      int i = 0; 
      StringBuffer sb = new StringBuffer(); 
      while ((i = is.read()) != -1) 
       sb.append((char)i); 
      System.out.println(sb.toString()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

和這個,我想以可視化的問候世界的消息,當我點擊GO Jbutton

package escudo; 

import java.awt.BorderLayout; 
import java.awt.EventQueue; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.EmptyBorder; 
import javax.swing.JTextArea; 
import javax.swing.JButton; 

public class test extends JFrame { 

    private JPanel contentPane; 

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

    public test() { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 450, 300); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 

     JTextArea textArea = new JTextArea(); 
     textArea.setBounds(48, 71, 324, 180); 
     contentPane.add(textArea); 

     JButton btnGo = new JButton("go"); 
     btnGo.setBounds(159, 23, 89, 23); 
     contentPane.add(btnGo); 
    } 
} 

回答

1

不要使用空佈局。 Swing旨在與Layout Managers一起使用。

當我點擊GO的JButton

首先你需要一個ActionListener添加到按鈕。請參閱How to Write an ActionListener上的Swing教程部分。 ActionListener中的代碼應該在你的類中調用一個方法,而不是一個單獨的類。

第一個包含來自perl腳本的輸出消息「hello world!」並且我想在我的jtextarea中看到此消息

然後,您需要將System.out.println(..)語句重定向到文本區域。檢查Message Console爲一種方法來做到這一點。