且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用JButtons制作棋盘

更新时间:2023-12-05 22:28:34

可能的原因之一是ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg"); ...

One of the likely causes is ImageIcon empty = new ImageIcon("/pieces/EmptySquare.jpg");...

图像的路径表明您正在使用嵌入式资源,但是ImageIcon(String)会将值当作文件来对待,您不能使用嵌入式资源来执行此操作,因为它们不是文件.

The path of the image suggest that you are using embedded resources, but ImageIcon(String) treats the value as if it were a file, you can't do this with embedded resources, they aren't files.

相反,您需要使用类似ImageIcon empty = new ImageIcon(getClass().getResource("/pieces/EmptySquare.jpg"));的东西.

Instead, you need to use something more like ImageIcon empty = new ImageIcon(getClass().getResource("/pieces/EmptySquare.jpg"));.

就个人而言,我建议您使用ImageIO.read(getClass().getResource("/pieces/EmptySquare.jpg")),因为如果由于某种原因而无法加载资源,则将引发异常,而后会静默地失败.

Personally, I'd recommend that you should be using ImageIO.read(getClass().getResource("/pieces/EmptySquare.jpg")) as this will throw an exception if the resource can not be loaded from some reason, rather then failing silently.

grid[x][y].add(square);也将不起作用,因为您尚未为grid[x][y]

grid[x][y].add(square); also won't work, as you've not assigned anything to grid[x][y]

grid[x][y] = new JPanel();
grid[x][y].add(square);

可能会更好,但是我不知道为什么在执行诸如...之类的操作时会这么做

Might work better, but I don't know why you're doing this, when doing something like...

JButton grid[][] = new JButton[8][8];

//...

grid[x][y] = square;

对于您要实现的目标似乎更合乎逻辑...

Would seem to be more logical for what you are trying to achieve...

已更新...

您应该使用board.add(grid[x][y]);而不是board.setContentPane(grid[x][y]);,否则,您将用按钮替换内容窗格...由于只能有一个内容窗格,因此您只会获得一个按钮...

Instead of board.setContentPane(grid[x][y]); you should be using board.add(grid[x][y]);, other wise you will replace the content pane with the button...since there can only be a single content pane, you'll only get one button...