2015-05-10 72 views
0

我想讓用戶點擊一個btnGenerate,然後生成一個隨機數字,該數字被分配給一個可以在eclipse中的應用程序窗口中的按鈕下面的框中打印出短語的短語。如何在GUI文本框而非Eclipse控制檯上打印輸出?

問題是隨機語句出現在Eclipse控制檯上,而不是我的GUI上的文本框。

任何幫助表示讚賞。這是我的代碼到目前爲止:

//generate crime button 

JButton generateBtn = new JButton("Generate Crime"); 
generateBtn.setBackground(Color.LIGHT_GRAY); 
generateBtn.setFont(new Font("HGHeiseiKakugothictaiW3", Font.BOLD, 20)); 
GridBagConstraints gbc_generateBtn = new GridBagConstraints(); 

gbc_generateBtn.fill = GridBagConstraints.BOTH; 
gbc_generateBtn.insets = new Insets(0, 0, 5, 5); 
gbc_generateBtn.gridx = 15; 
gbc_generateBtn.gridy = 5; 

frmHeroVillains.getContentPane().add(generateBtn, gbc_generateBtn); 
generateBtn.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 

     /*random number generator that generates a number between 1-4 and outputs a random crime to the updatePane depending on which 
     number was generated */ 
     int number = ((int) (Math.random()*4)+1); 
     switch (number) { 
     case 1: 
      System.out.println("Jewelry Heist on main street!"); 
      break; 
     case 2: 
      System.out.println("Mugging in China town!"); 
      break; 
     case 3: 
      System.out.println("Boeing 247 - Hijacked!"); 
     default: 
      System.out.println("Nothing to Report."); 
      break; 


     } 
    ; 
    JLabel updateLabel = new JLabel("UPDATE ALERT.... " + number); 
      GridBagConstraints gbc_updateLabel = new GridBagConstraints(); 
      gbc_updateLabel.gridheight = 3; 
      gbc_updateLabel.insets = new Insets(0, 0, 5, 5); 
      gbc_updateLabel.gridx = 15; 
      gbc_updateLabel.gridy = 12; 
      frmHeroVillains.getContentPane().add(updateLabel, gbc_updateLabel);} } 
); 
+0

那究竟是什麼問題呢? – Mureinik

+0

隨機語句出現在Eclipse控制檯上,而不是我的GUI上的文本框 –

+1

你希望更新什麼「文本框」? – MadProgrammer

回答

1

您需要將System.out.println(...)消息重定向到您自己的組件。

查看Message Console的一種方法來做到這一點。您可以將輸出重定向到JTextAreaJTextPane

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

//Must throws Exception 

    JPanel myOutput = new JPanel(); 
    myOutput.setVisible(true); 
    myOutput.setBackground(Color.GRAY); 

    JTextArea mynewText = new JTextArea(); 
    myOutput.add(mynewText); 

    URL oracle = new URL("http://www.oracle.com/"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(
      oracle.openStream())); 
//InputStreamReader wrapped in BufferedReader 

    String inputLine; 
    inputLine = in.readLine(); 
    mynewText.setText(inputLine); 

    in.close(); 

//In the target window class 
mainWindow.add(myOutput); 
相關問題