[英]can't change ImageIcon from anonymous class inside a JPanel
I'm currently building a picture sorter. 我目前正在建立图片分类器。 I have a
JList
which has filenames, to the left of this I have an ImageIcon
which should show the picture for the current file_chosen
in the JList
. 我有一个包含文件名的
JList
,在它的左侧,我有一个ImageIcon
,应该在JList
显示当前file_chosen
的图片。
The problem is I can't find a way of updating the ImageIcon
contained inside a JLabel
; 问题是我找不到更新
JLabel
包含的ImageIcon
的方法; since the change appears inside the anonymous class where the ListSelectionListener()
is. 因为更改出现在
ListSelectionListener()
所在的匿名类中。
Below is the code: 下面是代码:
public class MemeList extends JPanel{
public MemeList(){
// load/update the file list.
updateFileList();
this.setLayout(new GridBagLayout());
JPanel east = new JPanel();
east.setLayout(new GridBagLayout());
gbc.gridx = 1;
gbc.gridy = 0;
this.add(east,gbc);
west = new JPanel();
west.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
this.add(west,gbc);
filearray = flist.toArray(new String[flist.size()]);
list = new JList(filearray);
list.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
}
}
});
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2 = new JLabel("", meme_preview_icon, JLabel.CENTER);
gbc.gridx = 0;
gbc.gridy = 0;
west.add(label2,gbc);
updateIcon();
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
pane.setPreferredSize(new Dimension(320, 340));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0,0,0,0);
east.add(pane, gbc);
}
Below here is the method for changing ImageIcon
以下是更改
ImageIcon
的方法
public void updateIcon(){
//west.removeAll();
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2.setIcon(meme_preview_icon);
west.revalidate();
west.repaint();
}
I figured out the problem with my flatmate. 我发现我室友的问题。
I just needed to call the method updateIcon()
inside the ListSelectionListener()
. 我只需要在
ListSelectionListener()
内部调用方法updateIcon()
ListSelectionListener()
。 I got confused because it told me before it had to be static and then the listener can't be static. 我很困惑,因为它告诉我必须是静态的,然后侦听器不能是静态的。 But there it is.
但是有。
list.addListSelectionListener(new ListSelectionListener()
@Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
updateIcon();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.