[英]Refreshing JLabel - Java
I have some problems with JLabels and Frames.. 我在使用JLabel和Frames时遇到一些问题。
I have the following code: 我有以下代码:
list.addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
//System.out.println(e.getFirstIndex());
String selectedFile = list.getSelectedValue().toString();
System.out.println("Selected file " + selectedFile);
JLabel label;
ImageIcon icon = new ImageIcon("C:\\Users\\danie\\Pictures\\" + selectedFile);
// frame.setSize(1047, 680);
label = new JLabel(icon);
//label.setSize(100,100);
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
I want to refresh the label in the center of the borderlayout if a item in a JList is selected. 如果选择了JList中的项目,我想刷新borderlayout中心的标签。 But with this code, the old image is futher displayed and the new image is only drawed behind the existing image.
但是使用此代码,将进一步显示旧图像,而新图像仅绘制在现有图像后面。
Could anyone help me? 有人可以帮我吗? :)
:)
First you are creating a new JLabel instance instead of working on the existing one. 首先,您要创建一个新的JLabel实例,而不是处理现有实例。 What you actually want to do is:
您实际要做的是:
labe.setIcon(icon);
This will automatically refresh the element. 这将自动刷新元素。
Suggestions: 意见建议:
setIcon(...)
method setIcon(...)
更改显示在该 JLabel中的图标setIcon(...)
方法 revalidate()
or repaint()
here as this should be done if you change components held within a container, such as if you removed the original JLabel from the JFrame's contentPane and swapped in a new one. revalidate()
或repaint()
,因为如果更改了容器中保存的组件,例如从JFrame的contentPane中删除了原始JLabel并交换了一个新的JLabel,则应该这样做。 Note that I do not recommend that you do this as it is over-complicating what should be a simple thing -- swapping icons. ArrayList<Icon>
or a HashMap<String, Icon>
), and then in your listener code, extract the correct icon, and put it into the existing JLabel. ArrayList<Icon>
或HashMap<String, Icon>
)中,然后在您的侦听器代码中,提取正确的图标,并将其放入现有的 JLabel中。 You are not using the same JLabel it seems. 您似乎没有使用相同的JLabel。 You should alter the label you already have, not create a new one.
您应该更改已经拥有的标签,而不要创建新标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.