[英]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.