Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8240155
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T20:23:28+00:00 2026-06-07T20:23:28+00:00

I am trying to load the same jlabel stored image twice into a gridlayout

  • 0

I am trying to load the same jlabel stored image twice into a gridlayout panel, however instead of creating two instances of the image, the image is only displayed once then moved.

How can I store the same JLabel position in the pieces array into more than one JLabel in the boardLabels array.

Thanks 🙂

public static JPanel boardPanel = new JPanel(new GridLayout(4, 0));
public static JLabel pieces[] = new JLabel[2];
private static JLabel[] boardLabels = new JLabel[4];

public MainFrame() {
    pieces[0] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece1.png"));
    pieces[1] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece2.png"));

    this.add(boardPanel);
    displayGUIboard();
}


public static void displayGUIboard() {

    //ERROR - the label in pieces[0] is not copied into both boardLabels [0] and [1]
    boardLabels[0] = pieces[0];
    boardLabels[1] = pieces[0];

    boardPanel.add(boardLabels[0]);
    boardPanel.add(boardLabels[1]);
}

public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.setVisible(true);
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

This works

    boardLabels[0] = new JLabel(pieces[1]);
    boardLabels[1] = new JLabel(pieces[1]);

when using ImageIcons, but I want to avoid this since to update the board I will have to remove then reload the JLabels. I would prefer to just update the already loaded labels.

edit
I tried this before but it throws a null pointer exception…

    boardLabels[0].setIcon(pieces[1]);
    boardLabels[1].setIcon(pieces[1]);

    boardPanel.add(boardLabels[0]);
    boardPanel.add(boardLabels[1]);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T20:23:30+00:00Added an answer on June 7, 2026 at 8:23 pm

    Don’t do this since you can’t add the same component more than once to a visualized container. Better to use multiple JLabels but have them use the same ImageIcon. ImageIcons can be used more than once with ease:

    public MainFrame() {
        pieceIcon[0] = new ImageIcon(System.getProperty("user.dir") + 
            "/images/piece1.png");
        pieceIcon[1] = new ImageIcon(System.getProperty("user.dir") + 
            "/images/piece2.png");
    
        this.add(boardPanel);
        displayGUIboard();
    }
    
    
    public void displayGUIboard() {
        boardPanel.add(new JLabel(pieceIcon[0]);
        boardPanel.add(new JLabel(pieceIcon[0]);
    }
    

    As an aside: note that none of your variables should be static.

    Edit: regarding your recent edit:

    This works

    boardLabels[0] = new JLabel(pieces[1]);
    boardLabels[1] = new JLabel(pieces[1]);
    

    when using ImageIcons, but I want to avoid this since to update the board I will have to remove then reload the JLabels. I would prefer to just update the already loaded labels.”

    Solution
    No you don’t have to change JLabels at all. Keep your JLabels where they are, but simply swap the icons that they hold using the JLabel setIcon(...) method.

    Edit
    Also, don’t confuse variables with objects. Even if you create a bunch of JLabel variables, if they all refer to the same JLabel object, you still can’t add a JLabel object more than once to a container.

    Edit You state:

    The code is a part of the display function for a game. An array of integers will represent the board which is interpreted (but not in the above code) and the correct Jlabel images will be placed into a gridlayout panel to display the gui of the board. I have gotten the display code to work fine, but in my current version it removes the jlabels from the board then creates new JLabels(piece…)… but i would prefer it to update itself from the integer array rather than removing the labels, reading the array, then recreating the labels.

    So create a JPanel that uses GridLayout and fill it with unchanging JLabels. Then simply change the icons held by the JLabels based on the values held by the int array. You could create a method that simplifies and automates this process.

    Edit regarding:

    edit I tried this before but it throws a null pointer exception.

    Then solve this as you would any NPE. Find out which line throws the NPE, check the variables on the line, at least one is null, and then fix it so that you initialize the variable before trying to use it.

    Edit
    for example:

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.image.BufferedImage;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GridExample extends JPanel {
       public static final int[][] MAP = {
          {1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2},
          {1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2},
          {1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2},
          {1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2},
          {1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2},
          {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2},
          {1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2},
          {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2},
          {1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2},
          {1, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2},
          {1, 1, 1, 1, 1, 1, 0, 0, 0, 2, 2}
       };
    
       public static final Color[] COLORS = {};
       private JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length];
    
       public GridExample() {
          setLayout(new GridLayout(MAP.length, MAP[0].length));
          for (int r = 0; r < labelGrid.length; r++) {
             for (int c = 0; c < labelGrid[r].length; c++) {
                labelGrid[r][c] = new JLabel();
                labelGrid[r][c].setIcon(Ground.getGround(MAP[r][c]).getIcon());
                add(labelGrid[r][c]);            
             }
          }
       }
    
       private static void createAndShowGui() {
          GridExample mainPanel = new GridExample();
    
          JFrame frame = new JFrame("GridExample");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    enum Ground {
       DIRT(0, new Color(205,133, 63)), GRASS(1, new Color(0, 107, 60)), 
       WATER(2, new Color(29, 172, 214));
       private int value;
       private Color color;
       private Icon icon;
    
       private Ground(int value, Color color) {
          this.value = value;
          this.color = color;
    
          icon = createIcon(color);
       }
    
       private Icon createIcon(Color color) {
          int width = 24; // how to use const in enum? 
          BufferedImage img = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
          Graphics g = img.getGraphics();
          g.setColor(color);
          g.fillRect(0, 0, width, width);
          g.dispose();
          return new ImageIcon(img);
       }
    
       public int getValue() {
          return value;
       }
    
       public Color getColor() {
          return color;
       }
    
       public Icon getIcon() {
          return icon;
       }
    
       public static Ground getGround(int value) {
          for (Ground ground : Ground.values()) {
             if (ground.getValue() == value) {
                return ground;
             }
          }
          return null;
       }
    
    }
    

    Which shows a GUI grid:
    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to load multiple elements with the same name from XML into
I am trying to load an image file (gif) which is stored locally in
I have been trying: to load an image into a window control with a
I'm trying to load a very basic Glade file from the same directory. However,
I'm trying to load a 3D model, stored locally on my computer, into Three.js
Trying to load content into a div, then on click load the previous content
Trying to load a small .txt file into mysql but get all my data
trying to load in a bunch of images into a list from a directory...my
Trying to load data into a drop down list when a user selects one
I am trying to load just the contents of a <div> into another <div>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.