2015-01-21 28 views
1

我試圖讓它在一個框架中有兩個面板。一個顯示4張卡片,另一個顯示一個按鈕。當點擊按鈕時,隨機選擇四張牌。初始化程序或單擊刷新時,卡片不顯示。 任何人都可以解釋我做錯了什麼,我需要做什麼來解決這個問題?JPanel組件在嘗試刷新它們後消失

這裏是我的代碼

import java.awt.event.*; 
import javax.swing.*; 
import java.awt.*; 

public class MyFrame extends JFrame{ 

    public MyFrame(){ 
     super("Random Cards"); 
     CardPanel cardPanel = new CardPanel(); 
     JPanel buttonPanel = new JPanel(); 
     JButton jbtRefresh = new JButton("Refresh"); 
     buttonPanel.add(jbtRefresh); 
     add(cardPanel, BorderLayout.CENTER); 
     add(buttonPanel, BorderLayout.SOUTH); 

     jbtRefresh.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e){ 
       cardPanel.refresh(); 
      } 
     }); 
    } 

    public static void main(String[] args){ 
     MyFrame f = new MyFrame(); 
     f.setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE); 
     f.setSize(500, 300); 
     f.setLocationRelativeTo(null); 
     f.setVisible(true); 
    } 

    public class CardPanel extends JPanel{ 
     JLabel l1; 
     JLabel l2; 
     JLabel l3; 
     JLabel l4; 

     void CardPanel(){ 
      refresh(); 
     } 

     void refresh(){ 
      l1 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png")); 
      l2 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png")); 
      l3 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png")); 
      l4 = new JLabel(new ImageIcon("image/card/" + (int)(1 + Math.random() * 54) + ".png")); 
      removeAll(); 
      add(l1); 
      add(l2); 
      add(l3); 
      add(l4); 
      repaint(); 
     } 
    } 
} 
+0

您將無法訪問'ActionListener'中的'cardPanel'變量。爲了做到這一點'cardPanel'必須是'final' – Titus 2015-01-21 00:10:15

+0

你在說什麼? 'final'是一個常量修飾符。 – 2015-01-21 00:11:06

+0

@Malik Brahimi他正試圖訪問'匿名內部類'中的變量。爲了做到這一點,變量必須是'final' – Titus 2015-01-21 00:31:05

回答

1

簡短的回答

呼叫revalidaterepaint之前調用refresh時...

更長,更合適的答案

Ç改爲使用CardLayout代替。見How to Use CardLayout更多細節

也...

  • 確保您正在創建/修改你只從事件分派線程的上下文中的用戶界面,看到Initial Threads瞭解更多詳情。
  • 您可能會考慮製作Card課程,該課程延伸至JPanel之類的課程,該課程負責展示特定的卡片。這樣,您可以簡單地計算出您需要的隨機卡片值,並不斷更新預先存在的實例,而不是每次都創建新的實例。一般來說,運行速度更快,是比較有效

尼特挑:你應該避免延長您的用戶界面的直接從頂層容器,如JFrame,他們往往可以鎖定到一個單一的使用情況,並使其難以在未來重用或擴展。您並不是真的在框架中添加任何新功能