我用几句话创建了一个枚举。我想在gui上显示随机选择一个单词,但是,我不确定如何实际显示随机单词。如果需要更多信息,请随时告诉我,谢谢!
这是枚举:
public enum Words {
RIFLE,RAILROAD,FARM,SLOPE,LEPERACHAUN,SONG,CREATOR,TENT,FORM,FOOD,DINNER,TICKET,NOVEL,SPARK,
KITTEN,GUST,SMOKE,HORSE,LOSS,BRAKE,JAZZ,BASEBALL,SIZZLE,LEOPARD,SPARROW,EGG,QUARTER,MULTIPLE,DUPLEX,VOICE,
GNU,UNDERWEAR,SAND,BED,CANNON,NOTEBOOK,CAUSE,DIRT,PYTHON,SWING,WORD,RAY,SNOW,TRUCK,SILVER,NERVE,DEATH,
SEASHORE,WATER,COBWEB;
public String toString() {
String name = name();
return name.substring(0, 1) + name.substring(1);
}
}
以下是我希望显示单词的视图:
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import acm.graphics.GLabel;
import acm.program.Program;
public class HangmanView implements MouseListener, ActionListener {
private static final int DEFAULT_SIZE = 600;
private static final Font FONT = new Font("Helvetica", Font.BOLD, 20);
private JLabel statusMsg;
private Words words;
HangmanGraphics Content = new HangmanGraphics(DEFAULT_SIZE/2,DEFAULT_SIZE/2);
Hangman game; // the controller
HangmanModel model; // the model
public HangmanView(Hangman game) {
final GLabel label = new GLabel(words.toString());
label.setFont(FONT);
game.add(label, DEFAULT_SIZE/4, DEFAULT_SIZE/4);
}
}
答案 0 :(得分:0)
您需要以下代码:
import java.util.Random;
public static void main(String[] args){
Random random = new Random();
int rand = random.nextInt(Words.values().length);
System.out.println(Words.values()[rand]);
}
它的作用是使用Random类创建一个从1到单词数的随机数(rand),然后使用索引rand(Words.values()[rand]
)打印出该元素。 Words.values()
返回枚举中所有单词的数组。