2014-01-25 55 views
0

我在CardLayout上關注YouTube上的教程。我下載了the original code,它工作得很好。但對於我試圖製作的程序,我需要一個單獨的類來運行應用程序(即單獨的類僅使用main方法),單獨的類爲JFrame,並且至少有一個單獨的類用於JPanel s。我嘗試分離代碼,但它爲我顯示一個空白JFrameCardLayout的問題

import java.awt.CardLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JPanel; 

public class CardJPanel extends JPanel 
{ 
    JPanel panelCont = new JPanel(); 
    JPanel panelFirst = new JPanel(); 
    JPanel panelSecond = new JPanel(); 
    JButton buttonOne = new JButton("Switch to second panel"); 
    JButton buttonSecond = new JButton("Switch to first panel"); 
    CardLayout cl = new CardLayout(); 

    public CardJPanel() 
    { 
     panelCont.setLayout(cl); 

     panelFirst.add(buttonOne); 
     panelSecond.add(buttonSecond); 
     panelFirst.setBackground(Color.BLUE); 
     panelSecond.setBackground(Color.GREEN); 

     panelCont.add(panelFirst, "1"); 
     panelCont.add(panelSecond, "2"); 
     cl.show(panelCont, "1"); 

     buttonOne.addActionListener(new ActionListener() 
     { 
      @Override 
      public void actionPerformed(ActionEvent arg0) 
      { 
       cl.show(panelCont, "2"); 
      } 
     }); 

     buttonSecond.addActionListener(new ActionListener() 
     { 
      @Override 
      public void actionPerformed(ActionEvent arg0) 
      { 
       cl.show(panelCont, "1"); 
      } 
     }); 
    } 
} 

import javax.swing.JFrame; 

public class Frame extends JFrame 
{ 
    public Frame() 
    { 
     CardJPanel panel = new CardJPanel(); 
     setContentPane(panel); 
     setVisible(true); 

// if I do this it displays the panel just fine 
     JPanel panel2 = new JPanel(); 
     panel.setBackground(Color.MAGENTA); 
     setContentPane(panel2); 
    } 
} 

import javax.swing.JFrame; 

public class Main 
{ 
    public static void main(String[] args) 
    { 
     Frame startFrame = new Frame(); 
     startFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     startFrame.setSize(450, 400); 
     startFrame.setVisible(true); 
    } 

} 

回答

1

CardJPanel你應該加入這一行:

this.add(panelCont); 

也許你展示它的權利之前:

public CardJPanel() 
{ 
    panelCont.setLayout(cl); 
    this.add(panelCont); 
    panelFirst.add(buttonOne); 
    panelSecond.add(buttonSecond); 
    panelFirst.setBackground(Color.BLUE); 
    panelSecond.setBackground(Color.GREEN); 

    panelCont.add(panelFirst, "1"); 
    panelCont.add(panelSecond, "2"); 

    this.add(panelCont); 
    cl.show(panelCont, "1"); 

    buttonOne.addActionListener(new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent arg0) 
     { 
      cl.show(panelCont, "2"); 
     } 
    }); 

    buttonSecond.addActionListener(new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent arg0) 
     { 
      cl.show(panelCont, "1"); 
     } 
    }); 

} 

你有JPanel panelCont但它實際上從來沒有使用。您想將其添加到JPanel(或CardJPanel)本身,以便顯示它。