我想製作一個神奇的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;
}
}
}
'開關(somevar)情況下, '不管':call_output_to_gui_function_here();' – 2014-11-24 16:43:06
設計建議:讓你的switch語句返回字符串(到一個變量),然後有一個** **行執行輸出。方式更易於維護。 – pamphlet 2014-11-24 16:52:06