[英]How to use Card layout?
我很難弄清楚什么是卡布局。 我閱讀了很多文章,並實現了這個小例子,以了解卡片布局的工作原理。 但是我無法理解某些方法(已注釋)。 有人可以幫我嗎(我使用命令行)。
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();
}
}
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
,您想要讓CardLayout
show
所需的視圖...
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
的容器的引用以及要顯示的視圖的名稱。
有關更多詳細信息,請參見如何使用CardLayout 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.