如何在Java中使用switch语句在GUI上打印?

时间:2014-11-24 16:39:46

标签: java switch-statement

我想制作一个神奇的8球类程序,但是,我不知道如何在GUI上打印出switch case语句。我不确定从这里做什么。我试着查看我的java书籍和互联网但是,我找不到任何东西。 这是我的代码:

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;
    }
}
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

System.out输出到控制台/命令行,而不是JFrame,您需要实际拥有一个UI元素来显示您的选项。 JLabel,或JTextArea,或类似的东西