java 刷新 JLabel 图标图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17480765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refreshing a JLabel icon image
提问by Austin
I'm displaying an image in a JFrame using a JLabel and setting it's icon.
我正在使用 JLabel 在 JFrame 中显示图像并设置它的图标。
It works the first time, but whenever I go to change the image, it remains what I set it the first time, so I've tried this and still the same result.
它第一次工作,但每当我去改变图像时,它仍然是我第一次设置的,所以我试过这个,结果仍然相同。
contentPane.remove(lblPlaceholder);
lblPlaceholder = null;
lblPlaceholder = new JLabel("");
lblPlaceholder.setBounds(10, 322, 125, 32);
contentPane.add(lblPlaceholder);
lblPlaceholder.setIcon(new ImageIcon("tempimage.png"));
How can I get it to change it's image? I've also tried repainting the JFrame with no results.
我怎样才能让它改变它的形象?我也试过重绘 JFrame 没有结果。
回答by MadProgrammer
Works fine for me. I think there is something else in your code you're not sharing. A SSCCEwould help clarify other issues.
对我来说很好用。我认为您的代码中还有其他内容您没有共享。一个SSCCE将有助于澄清等问题。
Some suggestions based on what you have provided...
根据您提供的内容,提供一些建议...
- Avoid
null
layouts (looks like you mightbe using one) - Avoid
setBounds
- 避免
null
布局(看起来您可能正在使用一种) - 避免
setBounds
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ShowLabelImage {
public static void main(String[] args) {
new ShowLabelImage();
}
private JLabel label;
private List<BufferedImage> images;
private int currentPic = 0;
public ShowLabelImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
images = new ArrayList<>(2);
try {
images.add(ImageIO.read(new File("path/to/pic1")));
images.add(ImageIO.read(new File("path/to/pic2")));
} catch (IOException exp) {
exp.printStackTrace();
}
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
JButton switchPic = new JButton("Switch");
switchPic.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentPic++;
if (currentPic >= images.size()) {
currentPic = 0;
}
label.setIcon(new ImageIcon(images.get(currentPic)));
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(label);
frame.add(switchPic, BorderLayout.SOUTH);
switchPic.doClick();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
回答by Andrew Thompson
There is no need to create a new label, and it is probably hindering things.
没有必要创建一个新标签,它可能会阻碍事情。
Change:
改变:
contentPane.remove(lblPlaceholder);
lblPlaceholder = null;
lblPlaceholder = new JLabel("");
lblPlaceholder.setBounds(10, 322, 125, 32);
contentPane.add(lblPlaceholder);
lblPlaceholder.setIcon(new ImageIcon("tempimage.png"));
To:
到:
lblPlaceholder.setIcon(new ImageIcon("tempimage.png"));
See also this working example.
另请参阅此工作示例。
Further tips
更多提示
- Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space. E.G. The above GUI uses a
GridBagLayout
to center the image within aJScrollPane
. - For help with layouts provide ASCII art of the GUI as it should appear in smallest size and (if resizable) with extra width/height.
- For better help sooner, post an SSCCE.
- Java GUI 可能必须在多个平台上工作,使用不同的屏幕分辨率并使用不同的 PLAF。因此,它们不利于元件的精确放置。要为健壮的 GUI 组织组件,请使用布局管理器或它们的组合,以及用于空白区域的布局填充和边框。EG 上面的 GUI 使用 a
GridBagLayout
将图像置于JScrollPane
. - 为了帮助布局,请提供 GUI 的 ASCII 艺术,因为它应该以最小的尺寸出现,并且(如果可调整大小)具有额外的宽度/高度。
- 为了尽快获得更好的帮助,请发布SSCCE。
回答by kazmer
If you look at the ImageIcon constructor, you'll see that it loads the icon with this method: image = Toolkit.getDefaultToolkit().getImage(location);
The documentation of this method says:
如果您查看 ImageIcon 构造函数,您会看到它使用此方法加载图标:此方法image = Toolkit.getDefaultToolkit().getImage(location);
的文档说:
* Returns an image which gets pixel data from the specified URL.
* The pixel data referenced by the specified URL must be in one
* of the following formats: GIF, JPEG or PNG.
* The underlying toolkit attempts to resolve multiple requests
* with the same URL to the same returned Image.
To refresh the ImageIcon every time you load it from the same filename, you should add something random to the end of the URL, without changeing the actual filename. Something like this should work:
要在每次从相同文件名加载 ImageIcon 时刷新它,您应该在 URL 末尾随机添加一些内容,而不更改实际文件名。这样的事情应该工作:
try {
URL url = new URL(file.toURI().toString()
+ "?" + System.currentTimeMillis());
jLabel1.setIcon(new ImageIcon(url));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}