如何在另一个 JLabel 的图标上显示 JLabel 的图标



假设我正在构建一个带有摇摆的国际象棋应用程序。我正在使用jlabels数组来表示棋盘格(每个都有其适当的图标集作为轻度/深色阴影框)。我已经创建了另一组Jlabels来保存国际象棋棋子的图标,但是我对Swing不太熟悉,以了解如何实现它们以显示在棋盘上。有人知道有什么技术吗?

我写了一个小示例,该示例构建了一个窗口,彼此之间构建了两个jlabels。

请注意, grey.jpg pawn.png 图像具有128x128尺寸,而Pawn One具有透明的背景(这样,我阻止了Pawn Image的背景隐藏灰色矩形盒)。

这是构建窗口并添加组件的棋盘类:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ChessFrame extends JFrame {
    private JPanel panel;
    private JLabel greyBox;
    private JLabel pawn;

    public ChessFrame() {
        super();
        /* configure the JFrame */
        this.setSize(300, 300);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void addComponents() {
        panel = new JPanel();
        greyBox = new JLabel(new ImageIcon("images/grey.jpg"));
        pawn = new JLabel(new ImageIcon("images/pawn.png"));
        /* add the pawn inside the grey box (we have to set a layout for the grey box JLabel) */
        greyBox.setLayout(new BorderLayout());
        greyBox.add(pawn);
        /* add grey box to main JPanel and set its background to white so we observe the result better */
        panel.add(greyBox);
        panel.setBackground(Color.WHITE);
        this.getContentPane().add(panel);
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
    }
}

这是一个创建棋盘对象并显示窗口的主要类:

public class Main {
    public static void main(String[] args) {
        ChessFrame chessFrame = new ChessFrame();
        chessFrame.addComponents();
        chessFrame.setVisible(true);
    }
}

最新更新