【问题标题】:Adding a JLabel with a transparent background icon over another JLabel and display both在另一个 JLabel 上添加一个带有透明背景图标的 JLabel 并同时显示
【发布时间】:2017-06-24 11:15:47
【问题描述】:

我一直在我的大学学习 Java,我很新,但我正在努力提高自己的水平。 我正在尝试设置一个显示草瓷砖网格的 GUI(使用带有草图标的 JLabels),但我想在草顶部添加一些其他图标(字符图标),以便我可以看到站在上面的角色草地。我想我可以通过使用 JLayeredPane 并在同一位置添加另一个 JLabel 但具有更高的层优先级来做到这一点,但它似乎不起作用。关于我应该怎么做的任何建议?

谢谢:)

编辑:我设法使用 MigLayout 和 setOpaque(false) 指令来做到这一点。谢谢你的回答:)

【问题讨论】:

  • 有很多方法可以做到这一点。您可以将布局管理器应用于草标签,这样您就可以向它们添加组件,这样您就可以使用GridLayout 来简单地显示草瓷砖,或者您可以制作一个使用草图像绘制背景的自定义组件,再次向其添加布局管理器,以便您可以添加组件。两者都有优点,自定义面板更复杂,但可以让您更好地控制组件的大小,标签更简单,但只会是图标的大小,而不是内容
  • 如果标签是图标的大小就可以了。如果您有时间,能否请您发布一个示例代码?
  • 不要用“我解决了这个问题...”来编辑您的问题,请添加您的问题的答案(包括minimal reproducible example 形式的代码),以便任何来看这个的人将来的问题,如果他们遇到类似的问题或疑问,知道该怎么做。 @MadProgrammer 没有为此发布示例代码,因为您没有发布可使用的代码,但这里有一些 exampleshere

标签: swing user-interface icons jlabel jlayeredpane


【解决方案1】:

这是我用来解决这个问题的代码片段。

    private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 457, 330);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLayeredPane panel = new JLayeredPane();
    panel.setBounds(0, 0, 457, 330);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    JPanel background = new JPanel();
    background.setBounds(0, 0, 457, 330);
    panel.add(background);
    background.setLayout(new MigLayout("","",""));
    //In my particular problem I used some constraints, but they're not needed

    backgroundLabels = new JLabel[NCOLS][NROWS];
    for (int i = 0; i < NCOLS; i++)
        for (int j = 0; j < NROWS; j++) {
            backgroundLabels[i][j] = new JLabel(backgroundIcon);
            //Assuming you have a backgroundIcon variable where you saved your icon
            background.add(backgroundLabels[i][j], "cell " + i + " " + j);
        }

    JPanel characterPanel = new JPanel();
    panel.setLayer(characterPanel, 1);
    characterPanel.setBounds(0, 0, 457, 330);
    panel.add(characterPanel);
    characterPanel.setOpaque(false);
    characterPanel.setLayout(new MigLayout("","",""));

    characterLabels = new JLabel[NCOLS][NROWS];
    for (int i = 0; i < NCOLS; i++)
        for (int j = 0; j < NROWS; j++) {
            characterLabels[i][j] = new JLabel("");
            //Creates empty character labels. You can then add icons using setIcon()
            characterPanel.add(characterLabels[i][j], "cell " + i + " " + j);
        }

}

【讨论】:

猜你喜欢
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2016-01-11
  • 2013-03-17
  • 2016-06-16
相关资源
最近更新 更多