从JButton更改JLabel的图像

时间:2014-05-18 09:01:12

标签: java image swing jlabel

我已经搜索了高低的答案,但我无处可去。我不知道以前是否有其他人遇到过这个问题,但我感谢所有的帮助,谢谢。

我有一个100 x 100的标签网格,让我解释一下我是如何创建的。我有一个创建和填充字符串数组的方法。下一个方法创建一个标签数组,然后使用setText()方法将String(从先前方法创建)添加到标签。之后的方法获取那些JLabel并将它们添加到Grid Layout的JPanel中。然后我将JPanel添加到JScrollPane,JScrollPane被添加到另一个带有空边框的JPanel,最后的JPanel被添加到JFrame中。这就是我创建网格的方式,我很满意,我不想改变它。

我唯一的问题是我无法从main方法修改JLabel的图像。我可以从创建和填充JLabel的方法中执行此操作,我可以从创建网格的方法中执行此操作,但我无法从main方法更改JLabel的图像。我试图为此创建一个新方法,并在main方法中调用它 - 没有。我也尝试从按钮的ActionListener中更改它 - 再没有。我知道这是可能的,我知道我错过了一些非常明显的事情。

请帮忙解决这个问题?下面是代码,如果你运行它并单击按钮,你会发现没有任何反应。然而,最奇怪的是我可以从几乎任何地方改变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();

}


}

有人可以帮帮忙吗?我昨天花了一整天的时间试图让这个工作起来但却没有到达任何地方。此外,我对此非常陌生,我在这堂课中所做的一切我都是在过去几周才学到的,所以如果你能和你好,请解释一下我需要做什么以及为什么。

非常感谢!

1 个答案:

答案 0 :(得分:2)

我没有太多时间仔细检查,但您不需要在线创建新的JLabel对象:

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

因为它已在代码的早期创建。你还应该换行

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

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

完成这些更改后代码运行正常。

顺便说一句。你的代码看起来有点难看;)尝试重构它;)

这是在我的电脑上运行的代码:

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

}


}