简体   繁体   中英

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. 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 . 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.

Just so I'm clear, you problem is directly related to setLayout(null); which is bad regardless of what you're doing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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