简体   繁体   English

将JLabel添加到JPanel的问题

[英]Issue with adding JLabel to JPanel

I'm looking to display an image on a JPanel, but when I run the code, the panel is blank. 我希望在JPanel上显示图像,但是当我运行代码时,面板为空白。 The method I'm attempting is a slightly modified version of this tutorial . 我尝试的方法是本教程的稍微修改后的版本。

I've confirmed that all methods in the code are actually called using println . 我已经确认代码中的所有方法实际上都是使用println调用的。 My frame and panel are visible, and I'm fairly certain I've added both the icon to the label, and the label to the panel. 我的框架和面板是可见的,并且可以肯定的是,我既已将图标添加到标签,又将标签添加到了面板。 What am I missing? 我想念什么?

The relevant parts of my code: 我的代码的相关部分:

public class SYSTEM
  public static void start() {
    GameFrame GF = new GameFrame();
    GamePanel GP = new GamePanel();
    GF.add(GP);
    GP.loadSprite("Player", new Dimension(0,0));
  }
}

public class GameFrame extends JFrame {
  public GameFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(SYSTEM.windowSize);
    setVisible(true);
  }
}

public class GamePanel extends JPanel {
  ArrayList<Sprite> sprites = new ArrayList<Sprite>();
  GamePanel() {
    setVisible(true);
    setSize(SYSTEM.windowSize);
    setLayout(null);
  }
  public void loadSprite(String spriteName, Dimension pos) {
    sprites.add(new Player());
    add(sprites.get(0).getIcon());
}

public class Sprite {
  protected JLabel icon;
  protected BufferedImage image;
  protected String filePath;
  protected Dimension pos;
  public JLabel getIcon() {
    return icon;
  }
}

public class Player extends Sprite {
  public Player() {
    filePath = "FILEPATH_OMITTED";
    pos = new Dimension(0,0);
    try {                
        image = ImageIO.read(new File(filePath));
    } catch (IOException e) {
        System.out.println(e);
    }
    icon = new JLabel(new ImageIcon(image));
  }
}

Don't use components for games, you've thrown out the layout manager which is responsible for determining the size and location of the components, but you've failed to compensate for it. 不要在游戏中使用组件,而是丢掉了负责确定组件大小和位置的布局管理器,但是您未能对此进行补偿。 I'd recommend that you use a custom painting approach instead, see Painting in AWT and Swing and Performing Custom Painting for starters. 我建议您改用自定义绘画方法,请参阅AWT中的 绘画和初学者的摇摆执行自定义绘画

Just so I'm clear, you problem is directly related to setLayout(null); 只是我很清楚,您的问题与setLayout(null);直接相关setLayout(null); which is bad regardless of what you're doing 不管你做什么都不好

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

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