2012-11-27 65 views
2

擺動轉換圖像我有2類定義是這樣的:一個按鈕

public class Cartes extends JPanel 
{ 
    private BufferedImage image; 
    protected int tabC[] = new int[9]; 
    public int randomC ; 

    public Cartes() 
    { 

    .......... 

    BufferedImage myPicture = null; 

    try { 
     myPicture = ImageIO.read(new File("images/"+randomC+".png")); 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    JLabel picLabel = new JLabel(new ImageIcon(myPicture)); 
    add(picLabel); 
    } 

    public void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    g.drawImage(image, 0, 0, null); // 
    } 
} 

注:randomC是在構造函數中讓我在隨機圖像選擇生成一個整數。

public class VueGeo extends JFrame 
{ 
    public Cartes pan = new Cartes(); 
    private JButton bouton = new JButton("Change"); 

    public VueGeo() 
    { 

    ... 

    container.add(pan, BorderLayout.CENTER); 

    bouton.addActionListener(new BoutonListener()); 

    ... 

    this.setContentPane(container); 

    this.setVisible(true); 

    } 

    class BoutonListener implements ActionListener 
    { 
    public void actionPerformed(ActionEvent arg0) { 
     ???????? 
    } 
    } 
} 

的問題是我不知道要放什麼actionPerformed爲了讓我改變形象每當我上的更改單擊。有人有想法嗎?

+2

1)請使用一致的和邏輯的縮進代碼塊。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

3

請setter方法中的Cartes:

public void setImage(BufferedImage i) 
{ image = i; } 

然後,在的actionPerformed,

cartes.setImage((whatever image you would like)); 
cartes.repaint(); 
+0

(對不起,我不能縮進)感謝您的幫助,但是當我點擊更改,它不會改變任何T_T,這裏我輸入的actionPerformed: BufferedImage Picture = null; \t \t \t嘗試{ \t \t \t \t圖片= ImageIO.read(新文件( 「圖像/ 8.png」)); \t \t \t}趕上(IOException的發送){ \t \t \t \t // TODO自動生成的catch程序塊 \t \t \t \t e.printStackTrace(); \t \t \t} \t \t pan.setImage(Picture); \t \t pan.repaint(); } – Exia0890

+0

問題解決了謝謝,我應該剛剛使用圖像,而不是在cartes中使用myPicture。 – Exia0890

+0

嗯,對不起,這是我第一次來這裏^^ – Exia0890