我用java写了一个拼图游戏的空壳,希望在菜单栏的下面划分为一个九宫格,为什么不能得到想要的结果? 10
importjava.util.*;importjava.awt.*;importjavax.swing.*;publicclassE{staticfinalintWID...
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class E {
static final int WIDTH = 600;
static final int HEIGHT = 400;
static JPanel contentPane;
static JButton button[];
public static void main(String args[]){
final JFrame jf = new JFrame("八数码问题");
contentPane = new JPanel();
button = new JButton[9];
GridLayout gird = new GridLayout(3, 3);
contentPane.setLayout(gird);
jf.setBounds(200, 200, 600, 600);
jf.setSize(WIDTH, HEIGHT);
jf.setVisible(true);
jf.setContentPane(contentPane);
JMenuBar jb = new JMenuBar();
JMenu jm = new JMenu("游戏");
JMenuItem ji1 = new JMenuItem("开始游戏");
JMenuItem ji2 = new JMenuItem("自动拼图");
JMenuItem ji3 = new JMenuItem("退出");
jm.add(ji1);
jm.add(ji2);
jm.addSeparator();
jm.add(ji3);
jb.add(jm);
jf.setJMenuBar(jb);
LinkedList<Integer> c = new LinkedList<Integer>();
for(int i=1; i<=9; i++)
c.add(i);
Collections.shuffle(c);
for(int i=1; i<=9; i++){
String d = Integer.toString(c.get(i-1));
button[i] = new JButton(d);
contentPane.add(button[i]);
}
}
} 展开
import java.awt.*;
import javax.swing.*;
public class E {
static final int WIDTH = 600;
static final int HEIGHT = 400;
static JPanel contentPane;
static JButton button[];
public static void main(String args[]){
final JFrame jf = new JFrame("八数码问题");
contentPane = new JPanel();
button = new JButton[9];
GridLayout gird = new GridLayout(3, 3);
contentPane.setLayout(gird);
jf.setBounds(200, 200, 600, 600);
jf.setSize(WIDTH, HEIGHT);
jf.setVisible(true);
jf.setContentPane(contentPane);
JMenuBar jb = new JMenuBar();
JMenu jm = new JMenu("游戏");
JMenuItem ji1 = new JMenuItem("开始游戏");
JMenuItem ji2 = new JMenuItem("自动拼图");
JMenuItem ji3 = new JMenuItem("退出");
jm.add(ji1);
jm.add(ji2);
jm.addSeparator();
jm.add(ji3);
jb.add(jm);
jf.setJMenuBar(jb);
LinkedList<Integer> c = new LinkedList<Integer>();
for(int i=1; i<=9; i++)
c.add(i);
Collections.shuffle(c);
for(int i=1; i<=9; i++){
String d = Integer.toString(c.get(i-1));
button[i] = new JButton(d);
contentPane.add(button[i]);
}
}
} 展开
1个回答
展开全部
您的button数组大小为9,但是button[i] = new JButton(d); 这里是从button[1]开始赋值的,也就是说button[0]没有被赋值,当你赋值到第9个值时,数组溢出,报错,所以可能会得不到你想要的结果.最后的循环改一下:
for(int i=1; i<=9; i++){
String d = Integer.toString(c.get(i-1));
button[i-1] = new JButton(d);
contentPane.add(button[i-1]);
for(int i=1; i<=9; i++){
String d = Integer.toString(c.get(i-1));
button[i-1] = new JButton(d);
contentPane.add(button[i-1]);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询