简体   繁体   English

从JButton更改JLabel的图像

[英]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. 我有一个100 x 100的标签网格,让我解释一下我是如何创建的。 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. 下一个方法创建一个标签数组,然后使用setText()方法将String(从先前方法创建)添加到标签。 Method after that takes those JLabels and adds them to a JPanel of Grid Layout. 之后的方法获取那些JLabel并将它们添加到Grid Layout的JPanel中。 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. 然后我将JPanel添加到JScrollPane,JScrollPane被添加到另一个带有空边框的JPanel,最后的JPanel被添加到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. 我唯一的问题是我无法从main方法修改JLabel的图像。 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. 我可以从创建和填充JLabel的方法中执行此操作,我可以从创建网格的方法中执行此操作,但我无法从main方法更改JLabel的图像。 I've tried to create a new method for this and call it in the main method - nothing. 我试图为此创建一个新方法,并在main方法中调用它 - 没有。 I've also tried to change it from a button's ActionListener - nothing again. 我也尝试从按钮的ActionListener中更改它 - 再没有。 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. 然而最奇怪的是我可以从几乎任何地方改变JLabel的背景颜色。

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! 非常感谢你!

I didn't have too much time to check it carefully but you don't need to create new JLabel object at line: 我没有太多时间仔细检查它,但您不需要在行创建新的JLabel对象:

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. 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();

}


}

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

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