2016-04-27 88 views
1

我的代碼中有2個JPanel。第一個是Furutsu7,它是包含我的遊戲的主要JPanel。第二個JPanel是Jbutton的開始。我試圖完成的是在用戶點擊Jbutton之後,Furutsu7 JPanel會出現。單擊Jbutton後更改JPanels

這是我創建按鈕的設置類。

public void setup(){ 
    JFrame f = new JFrame("Start "); 
    JPanel card1 = new JPanel(); 
    JPanel card2 = new JPanel(); 


    cards = new JPanel(new CardLayout()); 

    JButton Card1Button = new JButton("Start"); 
    card1.add(Card1Button); 
    JButton Card2Button = new JButton("Exit"); 
    card2.add(Card2Button); 

    cards.add(card1, "C1"); 
    cards.add(card2, "C2"); 

    f.add(cards, BorderLayout.CENTER); 

    f.setTitle("Furutsu"); 
    f.setSize(500, 300); 
    f.setLocationRelativeTo(null); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.setVisible(true); 



} 

我需要幫助的是我爲了切換到Furutsu JPanel而執行的操作。

public void actionPerformed(ActionEvent e) { 


} 
+0

crossposted:http://www.coderanch.c OM /噸/ 664974/GUI/JAVA /更改-面板單擊-的JButton – camickr

回答

5

使您的CardLayout成爲該類的一個字段,以便您可以更輕鬆地在actionPerformed方法中獲取它。否則,你需要撥打(CardLayout) cards.getLayout(),這是一件危險的事情。例如:

public class MyClass implements ActionListener { 
    private CardLayout cardLayout = new CardLayout(); 
    private JPanel cards = new JPanel(cardLayout); 

    public void setup(){ 
     JFrame f = new JFrame("Start "); 
     JPanel card1 = new JPanel(); 
     JPanel card2 = new JPanel(); 

     // cards = new JPanel(new CardLayout()); 

     JButton Card1Button = new JButton("Start"); 
     card1.add(Card1Button); 
     JButton Card2Button = new JButton("Exit"); 
     card2.add(Card2Button); 

     cards.add(card1, "C1"); 
     cards.add(card2, "C2"); 

     f.add(cards, BorderLayout.CENTER); 

     f.setTitle("Furutsu"); 
     f.setSize(500, 300); 
     f.setLocationRelativeTo(null); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 
    } 

然後你就可以直接引用它:

@Override 
public void actionPerformed(ActionEvent e) { 
    // now you can call methods on your cardLayout variable: 
    cardLayout.show(...); // I'll leave it to you to figure out what to put in here 
} 

更多關於CardLayout,請查看其tutorial

請注意,如果你只是想換入前進組件或向後的順序,請看CardLayout的其他方法,如next(cards)previous(cards)