[英]Making an image show up on a JButton
I'm trying to make a chessboard (8x8 grid) and fill it with background squares, but it always appears as a grid of empty squares. 我正在尝试制作一个棋盘(8x8网格)并用背景正方形填充它,但它始终显示为一个空正方形的网格。 The image is called
emptysquare.jpg
but it does have a background color. 该图像称为
emptysquare.jpg
但确实具有背景色。
How to I correctly add an image to a JButton
on the grid I have? 如何正确地将图像添加到我拥有的网格上的
JButton
?
The reason that your chessboard is empty is due to the fact that you call JFrame#setVisible
before adding your ChessSquare
buttons to your panel. 棋盘为空的原因是由于在将
ChessSquare
按钮添加到面板之前调用了JFrame#setVisible
。 Ensure all component have been added before making this call. 进行此调用之前,请确保已添加所有组件。
Also set the Icon
like this in ChessSquare
在
ChessSquare
也像这样设置Icon
ImageIcon empty = ...
setIcon(empty);
You need to call setIcon( empty )
in your constructor. 您需要在构造函数中调用
setIcon( empty )
。
It's allowed-but-awkward to call setVisible( )
before the squares are added, but if you do you may need to repack to get the layout right. 允许在添加正方形之前调用
setVisible( )
,但有点尴尬,但是如果这样做,您可能需要重新包装以正确放置布局。
The call to setLayout( )
must be moved before the loop. 对
setLayout( )
的调用必须在循环之前移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.