2013-03-23 59 views
1

我是新创建GUI的用户,并且无法刷新JLabel上的图像。我已经阅读过同样问题的人的其他问题,但没有任何答案对我有帮助。我有一个程序在每次单击JButton时都会掷骰子,如果结果是一个,我想要更改JLabel的图像。这里是我的GUI类的构造函数:()以上正在更新JLabel图标

private Panel panel; 
private Label label; 
private TextField text; 
private JButton roll; 
private ArrayList<ImageIcon> deck; 
private ArrayList<ImageIcon> discard; 
private JLabel pic; 
private JFrame f; 
private ImageIcon now; 
public Planechase() 
{ 
    f = new JFrame("Planechase"); 
    deck = new ArrayList<ImageIcon>(); 
    populate(); 
    Collections.shuffle(deck); 
    discard = new ArrayList<ImageIcon>(); 
    label = new Label("Planechase"); 
    text = new TextField(":)",8); 
    text.setEditable(false); 
    roll = new JButton("Roll"); 
    roll.addActionListener(
     new ActionListener() { 
      public void actionPerformed(ActionEvent e) 
      { 
       int i = (int)(Math.random()*6)+1; 
       System.out.println(i); 
       if(i==1) 
       { 
        text.setText("Planeswalk"); 
        discard.add(now); 
        now = deck.remove(0); 
        pic = new JLabel(now); 
        pic.updateUI(); 
       } 
       else if(i==6) 
       { 
        text.setText("Chaos"); 
       } 
       else 
       { 
        text.setText("Blank"); 
       } 
      } 
     }); 
    now = deck.remove(0); 
    pic = new JLabel(now); 
    f.getContentPane().setLayout(new FlowLayout()); 
    f.getContentPane().add(pic); 
    f.getContentPane().add(text); 
    f.getContentPane().add(roll); 
} 

我试着用updateUI,在类似的问题建议,但画面不会改变。我还应该尝试什么?

回答

2

您正在ActionListener中创建新的Jlabel,但未将其添加到容器中。您可以使用setIcon

pic.setIcon(now); 

一些旁注更新Icon

  • 正如您删除Icons在你JLabel使用,你将最终耗尽可用图标如果不重新添加,将导致IndexOutOfBoundsException
  • 一般混合AWT & Swing组件不是一个好主意。较老的AWT组件通常不尊重组件,并且经常隐藏其轻量级邻居。见here
+0

下面是一个相关的[示例](http://stackoverflow.com/a/12228640/230513)。 – trashgod 2013-03-24 02:08:38

+0

+1,星期天早上nitpick:从技术上讲,混合现在正好 - 大部分时间没有真正意图,但:-) – kleopatra 2013-03-24 09:09:08