简体   繁体   中英

How to add a picture to a JPanel using a JLabel

When I try to add my picture icon to a JLabel on a panel it doesn't show up at all. Can someone tell me what Im doing wrong? Here part of my code:

    public class GameWindow extends JFrame implements ActionListener
{
    ImageIcon myPicture = new ImageIcon("src/GUI/Images/Face copy.png");
    JLabel picLabel = new JLabel(myPicture);

public GameWindow()

{
    super("Game Window");
    this.setSize(1500, 800);
    this.setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    JPanel tryThis = new JPanel();
    tryThis.setLayout(new BorderLayout());
    this.add(tryThis, BorderLayout.CENTER);
    JPanel grid1 = new JPanel();
    tryThis.add(grid1);

    int e = 4;
    int f = 14;
    JPanel[][] grid = new JPanel[e][f];
    grid1.setLayout(new GridLayout(e,f));

    for(int g = 0; g < e; g++) {
       for(int h = 0; h < f; h++) {
          grid[g][h] = new JPanel();
          grid1.add(grid[g][h]);
          grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
       }
    }

    grid[3][3].add(picLabel);

Alright, I've tweaked your code slightly, but I managed to get it to display an image on grid 3,3 (Although I could only see the image after slightly resizing the screen)

public class GameWindow extends JFrame implements ActionListener {

    public GameWindow(){
        super("Game Window");

        setSize(1500, 800);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel tryThis = new JPanel();
        tryThis.setLayout(new BorderLayout());

        add(tryThis, BorderLayout.CENTER);

        JPanel grid1 = new JPanel();
        tryThis.add(grid1);

        int e = 4;
        int f = 14;
        JPanel[][] grid = new JPanel[e][f];
        grid1.setLayout(new GridLayout(e,f));

        for(int g = 0; g < e; g++) {
           for(int h = 0; h < f; h++) {
              grid[g][h] = new JPanel();
              grid1.add(grid[g][h]);
              grid[g][h].setBorder(BorderFactory.createTitledBorder("Info"));
           }
        }

        try {
            // Loads the image
            BufferedImage myPicture = ImageIO.read(MainClassNameGoesHere.class.getResource("/example.png"));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));

            // Displays the image
            grid[3][3].add(picLabel);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }

The main thing that I changed was the way that you are loading in the image. I hope this helps, and feel free to ask any questions.

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