- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the importance of the CardLayout class in Java?
The functionality of CardLayout arranges the components in a sequential manner and only one component is visible at one time and each component will be treated as one card.
CardLayout
- The CardLayout is different from the other layouts where the other layout managers attempt to display all the components within the container at once, the CardLayout displays only one component at a time.
- In the CardLayout, cards are usually placed in a container such as a JPanel. The components are placed into the card queue in the order in which they are added.
- The important methods of CardLayout are first(), last(), next(), previous() and show().
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutTest extends JFrame implements ActionListener { CardLayout card; JButton b1,b2,b3; Container con; CardLayoutTest() { con = this.getContentPane(); card = new CardLayout(40,30); con.setLayout(card); b1 = new JButton("Java"); b2 = new JButton("Python"); b3 = new JButton("Scala"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); con.add("a", b1); con.add("b", b2); con.add("c", b3); } public void actionPerformed(ActionEvent e) { card.next(con); } public static void main(String[] args) { CardLayoutTest clt = new CardLayoutTest(); clt.setTitle("CardLayout Test"); clt.setSize(350, 275); clt.setLocationRelativeTo(null); clt.setDefaultCloseOperation(EXIT_ON_CLOSE); clt.setVisible(true); } }
In the above example, we can use the CardLayout manager where only one component (Java) will be visible on the window. When we click on the window remaining components (Python and Scala) can be visible.
Output
Advertisements