2011-01-26 78 views
0

我的脚本有问题;我想重新绘制新的图像(另一个显示)当按下一个按钮,但按钮不会做任何事情......Java重绘图像

ActionListener one = new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       panel2.revalidate(); 
       panel2.repaint(); 
      } 
     }; 

     btn1.addActionListener(one); 



     JLabel test1 = new JLabel(myDeckOfCards.giveCardPlayer1().getImage()); 

     panel2.add(lab1); 
     panel2.add(test1); 
     panel2.add(pn5); 
     panel2.add(pn1); 
     panel2.add(btn1); 
+0

实际上,按钮的ActionListener的** **不做些什么 - 它重新绘制你的JPanel。但是,您不会更改显示的图像,因此重新绘制它将不起作用。我同意fd - 在JLabel的图标中显示您的图像。如果需要,JPanel可以容纳这个JLabel。 – 2011-01-26 03:21:34

+0

我不明白你是谁。对不起, – anvd 2011-01-26 03:42:25

回答

5

里面actionPerformed你需要得到你的JLabel的保持和呼叫setIcon()上它传递了新的形象。

有几种方法可以得到一个JLabel,一个是要确保你有宣布某处包含在你的actionPerformed方法的范围final变量,另一种是从panel2(不推荐)里面找到它。

你也可以在将它传递给你的ActionListener通过构造函数,如果你宣布一个全面的类用于这一目的。

编辑

final JLabel test1 = new JLabel(myDeckOfCards.giveCardPlayer1().getImage()); 

ActionListener one = new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     // Get 'anotherIcon' from somewhere, presumably from a similar 
     // place to where you retrieved the initial icon 
     test1.setIcon(anotherIcon); 
    } 
}; 

btn1.addActionListener(one); 

panel2.add(lab1); 
panel2.add(test1); 
panel2.add(pn5); 
panel2.add(pn1); 
panel2.add(btn1);