【问题标题】:Java/Swing layer labels on top if each otherJava/Swing 层标签在顶部,如果彼此
【发布时间】:2017-12-27 17:44:55
【问题描述】:

我知道这个问题已经被问过好几次了,但没有一个解决方案对我们有用。 我们正在重新创建一个游戏,它有一张世界地图,并且应该在每个国家都显示国旗。我们通过使用图形方法让它工作(有点),但这不是持久的,我们也不能通过 var 名称来处理标志。

这就是为什么我们希望在JLabel 中包含每个标志,并在gamePane 内绘制它们,但要在它们的特定坐标上。所以我们需要能够用z轴定位。

GamePane 有一个JLabel,里面有一个ImageIcon,应该形成背景。最重要的是,我们要创建标志

一些代码(可能没有帮助):-

    gamePane = new JPanel();
    [...]

    public void paintFlagLabel() {
    for (Country currentCountry : risiko.getCountryList()) {
        JLabel flag = new JLabel();
        int x = currentCountry.getX();
        int y = currentCountry.getY();

        if (currentCountry.getOwningPlayer().equals(this.player)) {
            flag.setIcon(new ImageIcon(greenFlag));
        } else {
            flag.setIcon(new ImageIcon(redFlag));
        }
        String coordinates = "pos " + x + " " + y;
        gamePane.add(flag, coordinates);
        gamePane.revalidate();
        gamePane.repaint();
    }
}

【问题讨论】:

    标签: java swing jframe jpanel z-axis


    【解决方案1】:

    我们正在重新制作一款包含世界地图的游戏,并且应该在每个国家/地区显示国旗。

    您可以轻松地将 JLabel 添加到任何其他组件,包括 Jlabel。

    基本代码是:

    JLabel background = new JLabel( new ImageIcon(...) );
    background.setLayout( null );
    
    JLabel flag = new JLabel( new ImageIcon(...) );
    flag.setSize( flag.getPrefferedSize() );
    flag.setLocation(....);
    background.add( flag );
    

    我们无法通过 var 名称来处理标志。

    您可以保留所有标志的 Hashmap:

    Hashmap<String, JLabel> flags = new Hashmap<String, JLabel>()
    flags.add("theCountryName", theFlag);
    

    然后,当您想要访问标志时,您只需使用Hashmapget(...) 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多