cardlayoutframe.java~4~
来自「java2参考大全上的例子的源码和自己的理解.」· JAVA~4~ 代码 · 共 76 行
JAVA~4~
76 行
package CardLayoutFrame;//CardLayoutFrame.javaimport java.awt.*;import javax.swing.*;import java.awt.event.*;public class CardLayoutFrame extends JFrame { JButton btPrevious = new JButton("前一张"); JButton btNext = new JButton("下一张"); /* A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered. */ JPanel flowPanel = new JPanel(new FlowLayout()); /* A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. */ JPanel cardPanel = new JPanel(new CardLayout()); int currentIndex = 0; public CardLayoutFrame() { this.getContentPane().add(flowPanel,BorderLayout.SOUTH); this.getContentPane().add(cardPanel,BorderLayout.CENTER); cardPanel.add(getCard(1),"Card1"); cardPanel.add(getCard(2),"Card2"); flowPanel.add(btPrevious); flowPanel.add(btNext); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { switchCard(); } }; btPrevious.addActionListener(listener); btNext.addActionListener(listener); this.setSize(300,200); this.setTitle("GardLayoutDemo"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.show(); } JPanel getCard(int index){ JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("<HTML><h1 style=color:red>"+ "这是第"+index+"张卡片"+ "</h1></HTML>" ); label.setHorizontalAlignment(JLabel.CENTER); panel.add(label); return panel; } void switchCard(){ CardLayout cl = (CardLayout)cardPanel.getLayout(); if (currentIndex==0){ currentIndex++; cl.show(cardPanel,"Card2"); }else{ currentIndex--; cl.show(cardPanel,"Card1"); } } public static void main(String[] args) { CardLayoutFrame frame = new CardLayoutFrame(); }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?