Crazziiii
Crazziiii

Reputation: 17

Change the image of a JLabel from JButton

I have searched high and low for the answer but I am getting nowhere. I don't know if anyone else has had this problem before and but I appreciate all help, thank you.

I have a 100 by 100 grid of labels and let me explain how I created that. I've got a method which creates and populates an array of Strings. The next method creates an array of labels and then adds the String (created from previous method) to the labels using the setText() method. Method after that takes those JLabels and adds them to a JPanel of Grid Layout. Then I've added the JPanel to a JScrollPane, the JScrollPane gets added to another JPanel with an empty border and this final JPanel gets added to the JFrame. So that's how I've created the grid and I'm happy with that, I don't want to change it.

My only issue is that I am unable to amend the image of the JLabels from the main method. I can do this from the method which creates and populate the JLabels, I can do it from the method which creates the grid, but I cannot change the image of a JLabel from the main method. I've tried to create a new method for this and call it in the main method - nothing. I've also tried to change it from a button's ActionListener - nothing again. I know it's possible and I know I've missed something really obvious.

Please could you help with this? Below is the code, if you run it and click on the button you'll notice nothing happens. However the strangest thing is that I can change the background colour of the JLabels from almost anywhere.

package roverMars;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ArraysGrid extends JPanel {

private static final long serialVersionUID = -464020590200143351L;

final int rows = 50, columns = 50;

static BufferedImage Ahead, Down, Left, Right;


public void ImageLoader() {

    try {
        Ahead = ImageIO.read(this.getClass().getResource("Ahead.png"));
        Down = ImageIO.read(this.getClass().getResource("Down.png"));
        Left = ImageIO.read(this.getClass().getResource("Left.png"));
        Right = ImageIO.read(this.getClass().getResource("Right.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Error occured: " + e);
        e.printStackTrace();
    }

}

public void StringArray(String[][] labelText) {
    int x = 1; // increment rows

    for (int i = 0; i < labelText.length; i++) { // x
        for (int j = 0; j < labelText.length; j++) { // y
            labelText[i][j] = Integer.toString(x); // populate string
            x++;
        }
    }
}

public void JLabelArray(JLabel[][] label, String[][] labelText) {

    ImageLoader();

    for (int i = 0; i < label.length; i++) { // x
        for (int j = 0; j < label.length; j++) { // y
            label[i][j] = new JLabel();
            label[i][j].setText(labelText[i][j]);
            label[i][j].setOpaque(true);
        }
    }
    // Testing to see if image appears
    label[0][0] = new JLabel(new ImageIcon(Down));
    label[1][0] = new JLabel(new ImageIcon(Right));

}

// Add Labels to Panel,
public void Grid(JPanel Grid, JLabel[][] label) {

    String x1[][] = new String[rows][columns];
    StringArray(x1);
    JLabelArray(label, x1);

    int gHeight = label.length, gWidth = label.length;
    Grid.setLayout(new GridLayout(gWidth, gHeight));

    for (int i = 0; i < label.length; i++) { // x
        for (int j = 0; j < label.length; j++) { // y
            Grid.add(label[i][j]);

        }
    }
}

public void Frame(JPanel finalPanel, JPanel Grid) {

    // Add Grid to Scroll Pane
    JScrollPane x4 = new JScrollPane(Grid);
    x4.setPreferredSize(new Dimension(700, 700)); // DO NOT DELETE THIS.
    x4.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    x4.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    // Add Scroll Pane to another Panel with the Border
    finalPanel.setBackground(new Color(153, 153, 204));
    finalPanel.setBorder(BorderFactory.createEmptyBorder(50, 25, 50, 50));
    finalPanel.add(x4);

}

// This method to button.
public static void setImage(JLabel l) {

    ArraysGrid ag = new ArraysGrid();

    ag.ImageLoader();

    l = new JLabel(new ImageIcon(Left));
}

static JLabel[][] label = new JLabel[50][50];

public static void main(String[] args) {



    ArraysGrid m = new ArraysGrid();


    JPanel grid = new JPanel();
    JPanel final1 = new JPanel();

    m.Grid(grid, label);
    m.Frame(final1, grid);

    JFrame f = new JFrame();
    f.setTitle("Project Testing");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(true);
    f.setVisible(true);
    f.setLocation(650, 50);
    f.setSize(800, 800);
    f.setAlwaysOnTop(true);
    f.setBackground(Color.black);

    f.add(final1);

    JButton button = new JButton("Click Here");

    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            System.out.println("Clicked");
            label[1][1].setBackground(Color.RED);
            label[2][1] = new JLabel(new ImageIcon(Ahead));
            System.out.println(label[2][1].getIcon());

            setImage(label[2][2]);
            // label[2][2].setIcon((Icon) Ahead); // This throws several errors

        }
    });

    f.add(button, BorderLayout.NORTH);



    f.pack();

}


}

Please can someone help with this? I've spent all day yesterday trying to get this to work but not getting anywhere. Also I'm very new to this, everything I've done in this class I only learnt in the last couple of weeks so if it's okay with you please could you explain what I need to do and why.

Thank you very much!

Upvotes: 0

Views: 1134

Answers (1)

pepuch
pepuch

Reputation: 6516

I didn't have too much time to check it carefully but you don't need to create new JLabel object at line:

label[2][1] = new JLabel(new ImageIcon(Ahead));

because it has been already created earlier in the code. You should also change line

label[2][2].setIcon((Icon)Ahead); // This throws several errors

to

label[2][2].setIcon(new ImageIcon(Ahead)); // This throws several errors

After these changes code works fine.

BTW. Your code looks a little bit ugly ;) Try to refactor it ;)

This is code which works on my computer:

package roverMars;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ArraysGrid extends JPanel {

private static final long serialVersionUID = -464020590200143351L;

final int rows = 50, columns = 50;

static BufferedImage Ahead, Down, Left, Right;


public void ImageLoader() {

    try {
        Ahead = ImageIO.read(this.getClass().getResource("Ahead.png"));
        Down = ImageIO.read(this.getClass().getResource("Down.png"));
        Left = ImageIO.read(this.getClass().getResource("Left.png"));
        Right = ImageIO.read(this.getClass().getResource("Right.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Error occured: " + e);
        e.printStackTrace();
    }

}

public void StringArray(String[][] labelText) {
    int x = 1; // increment rows

    for (int i = 0; i < labelText.length; i++) { // x
        for (int j = 0; j < labelText.length; j++) { // y
            labelText[i][j] = Integer.toString(x); // populate string
            x++;
        }
    }
}

public void JLabelArray(JLabel[][] label, String[][] labelText) {

    ImageLoader();

    for (int i = 0; i < label.length; i++) { // x
        for (int j = 0; j < label.length; j++) { // y
            label[i][j] = new JLabel();
            label[i][j].setText(labelText[i][j]);
            label[i][j].setOpaque(true);
        }
    }
    // Testing to see if image appears
    label[0][0] = new JLabel(new ImageIcon(Down));
    label[1][0] = new JLabel(new ImageIcon(Right));

}

// Add Labels to Panel,
public void Grid(JPanel Grid, JLabel[][] label) {

    String x1[][] = new String[rows][columns];
    StringArray(x1);
    JLabelArray(label, x1);

    int gHeight = label.length, gWidth = label.length;
    Grid.setLayout(new GridLayout(gWidth, gHeight));

    for (int i = 0; i < label.length; i++) { // x
        for (int j = 0; j < label.length; j++) { // y
            Grid.add(label[i][j]);

        }
    }
}

public void Frame(JPanel finalPanel, JPanel Grid) {

    // Add Grid to Scroll Pane
    JScrollPane x4 = new JScrollPane(Grid);
    x4.setPreferredSize(new Dimension(700, 700)); // DO NOT DELETE THIS.
    x4.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    x4.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    // Add Scroll Pane to another Panel with the Border
    finalPanel.setBackground(new Color(153, 153, 204));
    finalPanel.setBorder(BorderFactory.createEmptyBorder(50, 25, 50, 50));
    finalPanel.add(x4);

}

// This method to button.
public static void setImage(JLabel l) {

    ArraysGrid ag = new ArraysGrid();

    ag.ImageLoader();

    l = new JLabel(new ImageIcon(Left));
}

static JLabel[][] label = new JLabel[50][50];

public static void main(String[] args) {



    ArraysGrid m = new ArraysGrid();


    JPanel grid = new JPanel();
    JPanel final1 = new JPanel();

    m.Grid(grid, label);
    m.Frame(final1, grid);

    JFrame f = new JFrame();
    f.setTitle("Project Testing");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(true);
    f.setVisible(true);
    f.setLocation(650, 50);
    f.setSize(800, 800);
    f.setAlwaysOnTop(true);
    f.setBackground(Color.black);

    f.add(final1);

    JButton button = new JButton("Click Here");

    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            System.out.println("Clicked");
            label[1][1].setBackground(Color.RED);
            //label[2][1] = new JLabel();
            System.out.println(label[2][1].getIcon());

            setImage(label[2][2]);
            label[2][2].setIcon(new ImageIcon(Ahead)); // This throws several errors

        }
    });

    f.add(button, BorderLayout.NORTH);



    f.pack();

}


}

Upvotes: 2

Related Questions