我使用 JLabel 在 JFrame 中显示图像并设置它的图标。
它第一次工作,但是每当我去更改图像时,它仍然保持我第一次设置的内容,所以我尝试过这个,但结果仍然相同。
contentPane.remove(lblPlaceholder);
lblPlaceholder = null;
lblPlaceholder = new JLabel("");
lblPlaceholder.setBounds(10, 322, 125, 32);
contentPane.add(lblPlaceholder);
lblPlaceholder.setIcon(new ImageIcon("tempimage.png"));
我怎样才能让它改变它的形象?我也尝试过重新绘制 JFrame,但没有结果。
对我来说效果很好。我认为您的代码中还有一些您没有共享的内容。 ASSCCE将有助于澄清其他问题。
根据您提供的内容提出一些建议...
- Avoid
null
布局(看起来像你might正在使用一个)
- Avoid
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);
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)