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

时间:2017-02-17 06:00:16

标签: java swing jlabel imageicon

假设我正在构建一个带有摇摆的国际象棋应用程序。我正在使用一组JLabel来表示棋盘(每个都有适当的图标设置为浅/暗阴影框)。我已经创建了另一个JLabel数组来保存国际象棋棋子的图标,但我不熟悉swing,知道如何实现它们以显示在棋盘上。有人知道任何技术吗?

1 个答案:

答案 0 :(得分:0)

我写了一个小例子,它构建了一个窗口和两个JLabel。

请注意, grey.jpg pawn.png 图片尺寸为128x128,典当图片具有透明背景(这样我就可以防止pawn图片的背景隐藏灰色矩形框)。

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

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);
    }

}

这是一个Main类,它创建一个ChessFrame对象并显示窗口:

public class Main {

    public static void main(String[] args) {
        ChessFrame chessFrame = new ChessFrame();

        chessFrame.addComponents();
        chessFrame.setVisible(true);
    }

}
相关问题