我开发了基诺游戏,我对如何从随机变量绘制特定JLabel图块(基本上是JLabel数组的特定位置)感到困惑。我认为最好的想法是将这些标签和我的prob变量修改为ArrayLists,但它不起作用。我想要实现的主要和最后的事情是绘制数组的特定位置" a"如果用户按下rollButton,则从prob变量中获取价格。 我已经使用了几种方法,我认为我非常接近,但我希望得到你的帮助。
在这里你可以找到我的代码:
import java.util.Random;
public class Game {
private final int RANDOMNUMBER = 80;
int prob;
String res;
StringBuilder sb = new StringBuilder();
public void rNumbers() {
for (int x = 0; x <= 12; x++) {
Random d = new Random();
prob = d.nextInt(RANDOMNUMBER) + 0;
sb.append("-");
sb.append(prob);
}
}
public void delete(StringBuilder sb2, String s) {
int start = sb2.indexOf(s);
if(start < 0)
return;
sb2.delete(start, start + s.length());
}
}
和Gui班
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
public class GuiKino extends JFrame implements ActionListener {
private JPanel mainPanel;
private JPanel contentPanel;
private JPanel otherPanel;
private Color color;
private JTextField text;
private JTextField input;
private JButton rollButton;
private JButton clearButton;
Game t = new Game();
private JLabel[] a = new JLabel[80];
GridLayout gridLayout = new GridLayout();
StringBuilder user = new StringBuilder();
public GuiKino() {
this.setTitle("Keno");
// Create panels
mainPanel = new JPanel();
contentPanel = new JPanel();
otherPanel = new JPanel();
this.contentPanel = (JPanel) getContentPane();
contentPanel.add(otherPanel, BorderLayout.SOUTH);
contentPanel.add(mainPanel, BorderLayout.CENTER);
mainPanel.setLayout(new GridLayout(10, 10));
otherPanel.setLayout(new GridLayout(2, 4));
text = new JTextField("", 20);
input = new JTextField("", 20);
rollButton = new JButton("Draw");
rollButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
otherPanel.add(text);
otherPanel.add(input);
otherPanel.add(rollButton);
otherPanel.add(clearButton);
for (int j = 0; j < a.length; j++) {
a[j] = new JLabel("");
a[j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
// cell numbers
for (int l = 0; l < a.length; l++) {
a[l].setText("" + l);
}
for (int i = 0; i < a.length; i++) {
mainPanel.add(a[i]);
}
}
ArrayList<Integer> places = new ArrayList<Integer>(Arrays.asList(t.prob));
ArrayList<JLabel> label = new ArrayList<JLabel>(Arrays.asList(a));
public void colored() {
if(!Collections.disjoint(label, places)){
//change the color!
color=Color.RED;
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == rollButton) {
t.rNumbers();
text.setText(t.sb.toString());
colored();
}
if (e.getSource() == clearButton) {
text.setText("");
t.delete(t.sb, t.sb.toString());
}
}
}