简体   繁体   English

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

[英]How to display a JLabel's icon over another JLabel's icon

Let's say I'm building a chess app with swing. 假设我正在使用秋千构建国际象棋应用程序。 I'm using an array of JLabels to represent the checkerboard (each has its appropriate icon set as a lightly/dark shaded box). 我正在使用JLabels数组表示棋盘格(每个都有其适当的图标集,设置为浅色/深色阴影框)。 I've created another array of JLabels to hold the icons of the chess pieces, but I'm not familiar enough with swing to know how to implement them to display on top of the checkerboard. 我创建了另一个JLabel数组来容纳棋子的图标,但是我对挥杆并不熟悉,不知道如何实现将它们显示在棋盘上方。 Anyone know of any techniques? 有人知道任何技术吗?

I have written a small example that builds a window and two JLabels on top of each other. 我编写了一个小示例,该示例相互之间构建一个窗口和两个JLabel。

Note that the grey.jpg and pawn.png images have 128x128 size and the pawn one has transparent background (this way I prevent the background of the pawn image from hiding the grey rectangle box). 请注意, grey.jpgpawn.png图像的尺寸为128x128,而pawn的背景为透明(这样,我可以防止pawn图像的背景隐藏灰色矩形框)。

Here is the ChessFrame class that builds the window and adds the components: 这是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);
    }

}

And here is a Main class that creates a ChessFrame object and shows the window: 这是一个Main类,它创建一个ChessFrame对象并显示窗口:

public class Main {

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM