2014-12-04 163 views
0

我很難弄清楚什麼是卡片佈局。我閱讀了很多文章,並實施了這個小例子來了解卡片佈局如何工作。但我不明白一些方法(這是評論)。有人可以幫助我(我使用命令行)。如何使用卡片佈局?

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

class C_layout implements ActionListener 
{ 
    JButton b2; 
    JButton b1; 
    JFrame f1; 
    JPanel card1; 
    JPanel card2; 
    JPanel Jp; 
    void Example() 
    { 
    f1=new JFrame("CardLayout Exercise"); 
    f1.setLocationRelativeTo(null); 
    f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f1.setSize(500,500); 
    f1.setVisible(true); 

    Container cont=f1.getContentPane(); 
    cont.setLayout(null); 

    Jp=new JPanel(new CardLayout()); //<-- How to implement card layout here (MAIN PANEL) 
    f1.add(Jp); 
    Jp.setLayout //<-- Not sure what means here ERROR 
    card1=new JPanel(); // First panel 
    Jp.add(card1); 
    card2=new JPanel(); // Second panel 
    Jp.add(card2); 

    JLabel lb1=new JLabel("This is the first Panel"); 
    lb1.setBounds(250,100,100,30); 
    card1.add(lb1); 

    b1=new JButton("NEXT >>"); 
    b1.setBounds(350,400,100,30); 
    b1.addActionListener(this); 
    card1.add(b1); 


    JLabel lb2=new JLabel("This is the second Panel"); 
    lb2.setBounds(250,100,100,30); 
    card2.add(lb2); 

    b2=new JButton("<< PREV"); 
    b2.setBounds(250,300,100,30); 
    b2.addActionListener(this); 
    card2.add(b2); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
    if(e.getSource()==b1) 
    { 
    CardLayout cardLayout = (CardLayout) Jp.getLayout(); 
    cardLayout.show(card2,"2"); 
    } 
    if(e.getSource()==b2) 
    { 
    // I still haven't implemented this action listener 
    } 
    } 
} 

class LayoutDemo1 
{ 
    public static void main(String[] args) 
    { 
    C_layout c=new C_layout(); 
    c.Example(); 


    } 
} 

回答

3

cont.setLayout(null);是壞,壞主意,很快失去它...

你將需要以管理到您CardLayout參考。通過定義一個CardLayout實例字段開始......

private CardLayout cardLayout; 

現在,創建的CardLayout您的實例,並將其應用到您的面板...

cardLayout = new CardLayout(); 
Jp=new JPanel(cardLayout); 

這...

Jp.setLayout //<-- Not sure what means here ERROR 

沒有做任何事情,就Java而言這不是一個有效的陳述,事實上,它實際上是一種方法,它應該引用你所希望的LayoutManager但由於您已經在創建Jp的實例時完成了這項工作,因此您並不需要它...

您將需要一些方法來確定要顯示的組件, CardLayout做到這一點通過String名稱,例如...

card1=new JPanel(); // First panel 
Jp.add(card1, "card1"); 
card2=new JPanel(); // Second panel 
Jp.add(card2, "card2"); 

現在,在ActionListener,你要問CardLayoutshow所需的視圖...

public void actionPerformed(ActionEvent e) 
{ 
    if(e.getSource()==b1) 
    { 
     cardLayout.show(Jp1,"card2"); 
    } else if(e.getSource()==b2) 
    { 
     cardLayout.show(Jp1,"card1"); 
    } 
} 

請注意,爲使CardLayout#show正常工作,您需要爲其分配CardLayout的容器參考,並指定要顯示的視圖的名稱。

查看How to Use CardLayout瞭解更多詳情

+0

非常感謝:D! – 2014-12-04 06:03:37

+1

希望它有幫助... – MadProgrammer 2014-12-04 06:04:51

+0

你能解釋一些例子:如何顯示框架,它給了我一個空白的框架。我不明白CardLayout#顯示 – 2014-12-04 14:42:33