繁体   English   中英

JLabel图标在运行时未更改

[英]JLabel icon not changing during run-time

运行程序时,需要在运行时将图像添加到GUI中。 据我所知,从源文件获取图像是可行的:

public ImageIcon getImage()
{
    ImageIcon image = null;

    if (length > 6.0)
    {
        //TODO
    } else {

        try
        {
            image = new ImageIcon(ImageIO.read( new File("car.png")));
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "An Error occured! Image not found.", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    return image;
}

然后,我使用.setIcon()方法将图像添加到JLabel ,但是在GUI上没有任何更改。

public void addCarImage(Car newCar, int spaceNo)
{
    ImageIcon carImage;

    carImage = newCar.getImage();

    JOptionPane.showMessageDialog(null, "Car", "Car", JOptionPane.INFORMATION_MESSAGE, carImage);

    carList[spaceNo - 1] = newCar;
    carLabel[spaceNo - 1].setIcon(carImage);

}

添加了JOptionPane消息以查看图像是否实际加载,是否加载。

有任何想法吗? 我已经用谷歌寻找解决方案,如repaint()/revalidate()/updateUI() ,但它们没有用。

编辑-像这样添加carLabels (在添加图像之前)。 JLabels最初是空白的。

carLabel = new JLabel[12];

    for (int i = 0; i < carLabel.length; i++)
    {
        carLabel[i] = new JLabel();
    }


carPanel.setLayout(new GridLayout(3, 4));

for (int i = 0; i < 12; i++)
    {
         carPanel.add(carLabel[i]);
    }

请确保在旋梭上进行。 另外,请确保已正确加载图像。

这是我用来测试的简单代码,很好。

public class Main {
public static void main(String[] args) {
    final JFrame frame = new JFrame("TEST");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    final JLabel label = new JLabel();
    ImageIcon icon = null;

    try {
        icon = new ImageIcon(ImageIO.read(new File("C:\\images\\errorIcon.png")));
    } catch (IOException e) {
        e.printStackTrace();
    }

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(label, BorderLayout.CENTER);
    frame.setSize(200,200);

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            frame.setVisible(true);
        }
    });


    try {
        Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    final ImageIcon finalIcon = icon;
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if(finalIcon != null && finalIcon.getImageLoadStatus() == MediaTracker.COMPLETE){
               label.setIcon(finalIcon);
            }
        }
    });
}

}

雅里克

设置该值后,carLabel [i] .repaint()应该起作用

暂无
暂无

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

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