gpt4 book ai didi

java - JLabel 背景图片...奇怪的行为?

转载 作者:行者123 更新时间:2023-11-29 05:46:52 24 4
gpt4 key购买 nike

我有一个必须组成 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();
}
});
}
}

enter image description here

关于java - JLabel 背景图片...奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15538576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com