2013-02-11 1 views
16

こんにちは、この記事は既に投稿されていますが、私は懸命に見えて、わかりにくい他のコードを見つけました。私はJavaプログラミングの初心者で、ボタンを押して希望のパネルにどのように変更できるかについて、誰かが正しい方向に向けるようにしたいと思います。どんな助けも高く評価されるでしょう。私はこのコンセプトの仕組みを完全に理解しようとしています。カード・コンポーネントを追加するときの制約を指定してください任意のパネルに切り替えカードレイアウトを使用してパネルを変更する

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; // Packages used in this program imported  

public class onlineGame extends JFrame implements ActionListener 
{ 

    JPanel cards; 
    JButton button1, button2, button3; 

    public onlineGame() //This is the CONSTRUCTOR method 
    { 
     //The entry point into your program 
     setLayout(new FlowLayout()); //Use this for now. 
     setSize(810, 510); //Set the size of the JFrame 
     setTitle("Generic Card Game"); //Put Title on top of JFrame 
     setBackground(Color.yellow); 
     setResizable(false); 

     button1 = new JButton("THIS IS BUTTON 1"); 
     button2 = new JButton("THIS IS BUTTON 2"); 
     button3 = new JButton("THIS IS BUTTON 3"); 

     button1.addActionListener(this); 
     button2.addActionListener(this); 
     button3.addActionListener(this);  

     //Create the cards 

     JPanel card1 = new JPanel(); 
     card1.add(button1); 

     JPanel card2 = new JPanel(); 
     card2.add(button2); 

     JPanel card3 = new JPanel(); 
     card3.add(button3); 

     //Create the panel that contains the "cards". 

     cards = new JPanel(new CardLayout()); 

     cards.add(card1); 
     cards.add(card2); 
     cards.add(card3); 

     getContentPane().add(cards); 
     setVisible(true); //Make JFrame visible 
    } 

    public void actionPerformed(ActionEvent e) 
    {  
     if (e.getSource() == button1){  
      //What do i put here to change to Panel card2 or card3 and so on. 
     } 
    } 
    public static void main(String args[]) 
    {  
     new onlineGame(); // This calls the constructor and runs it  
    } 
} 
+0

(将来の訪問者向け)[OracleのCardLayoutのドキュメント](https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html)は非常に分かりやすいです。 – RustyTheBoyRobot

+0

これを閉じる理由はまったくありません。これは狭い問題ではありません。それは質問が来るほど広いです。 – Gary

答えて

24

cards.add(card1, "Card 1"); 
cards.add(card2, "Card 2"); 
cards.add(card3, "Card 3"); 

、異なるコンポーネントに反転する:に移動する

CardLayout cardLayout = (CardLayout) cards.getLayout(); 
cardLayout.show(cards, "Card 2"); 

次のコンポーネントを使用することができます:

cardLayout.next(cards); 

Read:CardLayout

+0

ありがとうございます。次のパネルに変更するのではなく、変更したいパネルを指定することはできますか? –

+0

@aboadamはい。 Reimeusはあなたにそれを達成する方法を正確に示しました。 'next'を使う代わりに、' CardLayout#show(Container、String) ' – MadProgrammer

+0

ありがとう! : –

関連する問題