我正在创建一个老虎机项目(为了好玩)。我正在 JTextField 中显示水果。我已经设法在 JTextFields 中显示随机水果,但随机水果是相同的,例如,结果将是 -> 橙色,橙色,橙色。或者它会是,猕猴桃,猕猴桃,猕猴桃。 ETC。 这是我的代码。
import java.awt.BorderLayout;...
import java.util.Random;
public class Game extends JFrame {
String [] fruits = { "Cherry", "Lemon", "Orange", "Grape", "Kiwi" };
String fruit = fruits[(int) (Math.random() * fruits.length)];
private JPanel contentPane;
private JTextField Slot_1;
private JTextField Slot_2;
private JTextField Slot_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game frame = new Game();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Slot_1 = new JTextField();
Slot_1.setText("----------------");
Slot_1.setEditable(false);
Slot_1.setBounds(41, 53, 95, 28);
contentPane.add(Slot_1);
Slot_1.setColumns(10);
Slot_2 = new JTextField();
Slot_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_2.setText("-----------------");
Slot_2.setEditable(false);
Slot_2.setColumns(10);
Slot_2.setBounds(183, 53, 95, 28);
contentPane.add(Slot_2);
Slot_3 = new JTextField();
Slot_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Slot_3.setText("---------------");
Slot_3.setEditable(false);
Slot_3.setColumns(10);
Slot_3.setBounds(317, 53, 95, 28);
contentPane.add(Slot_3);
JButton btn_Pull = new JButton("Pull");
btn_Pull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
}
});
btn_Pull.setBounds(145, 108, 166, 29);
contentPane.add(btn_Pull);
JButton btnMenu = new JButton("Menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnMenu.setBounds(383, 243, 61, 29);
contentPane.add(btnMenu);
}
}
谢谢
最佳答案
String fruit = fruits[(int) (Math.random() * fruits.length)];
水果的值(value)在类(class)开始时就固定了。
Slot_1.setText(fruit);
Slot_2.setText(fruit);
Slot_3.setText(fruit);
水果的值不会仅仅因为您将其分配给 3 个不同的文本字段而改变。
如果你想要随机值,那么你需要调用 random() 方法 3 次。也许是这样的:
Slot_1.setText( fruits[(int) (Math.random() * fruits.length)] );
...
或者创建一个返回随机字符串的方法:
private String getFruit()
{
return fruits[(int) (Math.random() * fruits.length)];
}
并使用:
slot_1.setText( getFruit() );
另外:
变量名称不应以大写字符开头(Slot_1...)。你的其他变量是正确的(水果,水果),所以要保持一致。
不要使用空布局。 Swing 被设计为与布局管理器一起使用。
关于java - 老虎机随机化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27788347/