我有一个必须组成 8x8 网格的图像,所以它是板的背景。
有人告诉我可以使用 ImageIcon 和 JLabel 来做到这一点,我试过了,但似乎不起作用。
- 它不允许我向它添加组件(piece,它也是一个 JLabel)。
- 此外,当程序正在运行时,我点击了一个方 block - 它消失了,这并不理想,因为它应该是背景。
代码如下:
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
square=new JLabel();
square.setIcon(icon);
chessBoard.add( square );
}
}
完整代码:http://pastebin.com/YdavUmGz
我是不是对这张背景图片做错了什么?
如有任何帮助,我们将不胜感激,在此先致谢。
最佳答案
你在找这样的东西吗?
import java.awt.*;
import javax.swing.*;
public class ChessBoard extends JFrame {
private JPanel panel;
public ChessBoard() {
panel = new JPanel();
panel.setLayout(new GridLayout(8, 8, 0, 0)); //Create the board
//Add JLabels
for (int i = 0; i < 64; i++) {
JLabel label = new JLabel();
label.setIcon(
new ImageIcon(getClass().getResource("images/face.png")));
panel.add(label);
}
//Add the panel to the JFrame
this.add(panel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ChessBoard();
}
});
}
}
关于java - JLabel 背景图片...奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15538576/