Here is my code.
I would like the window to look like this but I don't like the numbers to be written 1-36 like in this code. When I delete that code and try with:
Random r = new Random();
for(int k = 0; k < z; k++) {
and I define z=20;
that field that was in the first place with 1-36 number, is deleted.
My expected output is, to be a field like in the code below but the numbers to be different every time I open the game.
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 2, 1, 1));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 1, 1, 1));
frame.add(panel, BorderLayout.CENTER);
JPanel center = new JPanel();
center.setLayout(new GridLayout(9, 9, 1, 1));
int z = 0;
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 6; j++) {
JButton button = new JButton(Integer.toString(++z));
center.add(button);
}
}
frame.add(center, BorderLayout.CENTER);
frame.setVisible(true);
答案 0 :(得分:0)
您可以使用一种方法,该方法将在指定范围内添加随机数作为按钮的名称。这样的东西:
public class Frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(1, 2, 1, 1));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 1, 1, 1));
frame.add(panel, BorderLayout.CENTER);
JPanel center = new JPanel();
center.setLayout(new GridLayout(9, 9, 1, 1));
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 6; j++) {
JButton button = new JButton(Integer.toString(random(1, 6)));
center.add(button);
}
}
frame.add(center, BorderLayout.CENTER);
frame.setVisible(true);
}
private static int random(int min, int max) {
return (int) (Math.random() * (max - min) + min);
}
}