2015-10-18 144 views
1

我試圖添加事件偵聽器到我的「播放」按鈕,但每當我在播放按鈕中添加一個消失或我得到和錯誤。將事件偵聽器添加到JFrame

package hamster.race; 
import java.awt.*; 
import javax.swing.*; 

public class HamsterRace extends JFrame { 
    public HamsterRace(){ 
     super("HamsterRace"); 
     setLookAndFeel(); 
     setSize(350*3, 100*5); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     FlowLayout flo = new FlowLayout(); 
     setLayout(flo); 
     setVisible(true); 
     JButton Play = new JButton("Play"); 
     add(Play); 
     add(Play); 


    } 
    private void setLookAndFeel() { 
     try{ 
      UIManager.setLookAndFeel{ 
       "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" 
     }; 
     }catch (Exception exc) { 
      //ignore error 
     } 
    } 

    public static void main(String[] args) { 
     HamsterRace frame = new HamsterRace(); 


    } 

} 
+0

'調用setVisible(真);'應該是在構造函數中的最後一次通話。 – user1803551

回答

1

首先,變量名不能以大寫字符開頭。

JButton Play = new JButton("Play"); 
    add(Play); 
    add(Play); 

您只有一個組件。您不能兩次添加相同的組件。

所以基本的代碼如下:

//setVisible(true); 
    JButton play1 = new JButton("Play1"); 
    add(play1); 
    JButton play2 = new JButton("Play2"); 
    add(play2); 
    pack(); 
    setVisible(true);