2014-11-24 59 views
-2

我想製作一個神奇的8球類程序,但是,我不知道如何獲得在GUI上打印出的switch case語句。我不確定從這裏做什麼。我試圖看看我的Java書籍和互聯網,但我找不到任何東西。 這裏是我的代碼:如何獲得Java中的switch語句以便在GUI上打印出來?

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.util.Random; 
import javax.swing.*; 

public class Main extends JFrame { 
JLabel label = new JLabel("Enter a Yes or No question"); 
JTextField field = new JTextField(12); 
JButton button = new JButton("Enter"); 

public Main() { 
    super("MAGIC 8 BALL"); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setLayout(new FlowLayout()); 
    add(label); 
    add(field); 
    add(button); 
} 

public void actionPerformed(ActionEvent e) { 
    String question = field.getText(); 
    int ball; 
    Random r = new Random(); 
    ball = r.nextInt(20); 
    String answer = ball; 
    switch (ball) { 
    case 0: 
     System.out.println("It's certain"); 
     break; 
    case 1: 
     System.out.println("It's decidedly so"); 
     break; 
    case 2: 
     System.out.println("Without a doubt"); 
     break; 
    case 3: 
     System.out.println("Yes definitely"); 
     break; 
    case 4: 
     System.out.println("You may rely on it"); 
     break; 
    case 5: 
     System.out.println("Probably"); 
     break; 
    case 6: 
     System.out.println("Try again later"); 
     break; 
    case 7: 
     System.out.println("Better Not to Tell you"); 
     break; 
    case 8: 
     System.out.println("Cannot predict now"); 
     break; 
    case 9: 
     System.out.println("Cannot see reply right now"); 
     break; 
    case 10: 
     System.out.println("Concentrate and ask again"); 
     break; 
    case 11: 
     System.out.println("Don't count on it"); 
     break; 
    case 12: 
     System.out.println("My reply is no"); 
     break; 
    case 13: 
     System.out.println("Very doubtful"); 
     break; 
    case 14: 
     System.out.println("Outlook not so good"); 
     break; 
    case 15: 
     System.out.println("My sources say no"); 
     break; 
    case 16: 
     System.out.println("Yes"); 
     break; 
    case 17: 
     System.out.println("Signs point to yes"); 
     break; 
    case 18: 
     System.out.println("As I see it, yes"); 
     break; 
    case 19: 
     System.out.println("Yes definitely"); 
     break; 
    } 
} 
} 
+0

'開關(somevar)情況下, '不管':call_output_to_gui_function_here();' – 2014-11-24 16:43:06

+0

設計建議:讓你的switch語句返回字符串(到一個變量),然後有一個** **行執行輸出。方式更易於維護。 – pamphlet 2014-11-24 16:52:06

回答

0

的System.out輸出到控制檯/命令行,而不是到JFrame,實際上你需要有顯示你的選擇的UI元素。 JLabel或JTextArea或類似的東西

1

您應該創建一個JLabel實例變量,然後使用相應的switch語句對其進行更新,然後將JLabel添加到JFrame的面板。

JLabel message = new JLabel(); 

switch (ball) { 
    case 0: 
     message.setText("It's certain"); 
     break; 
    case 1: 
     message.setText("It's decidedly so"); 
     break; 
    case 2: 
     message.setText("Without a doubt"); 
     break; 
    //do this till case n