Java Tutorial
In java programming, we can also use card layout in JFrame to create a Graphical user interface (GUI) using JFrame class.
In Java JFrame, need to set the layout to add the components.
Card Layout is used to put the components as a card in the JFrame, and only one component is visible every time.
CardLayout need a listener and event to show all the components but only one component visible every time.
setLayout(new CardLayout());
This java code uses card layout to arrange the 4 button components.
// importing swing package for JFrame, Jbutton controls import javax.swing.*; // importing to use Container class import java.awt.*; // importing to use event listeners import java.awt.event.*; public class CardLayoutTest extends JFrame { private CardLayout cl = new CardLayout(); private Container panel = getContentPane(); public CardLayoutTest(){ // Setting Title to the JFrame GUI setTitle("Card Layout Test Java Code"); // Adding buttons using Grid Layout JButton button1 = new JButton("Button1"); button1.setBackground(Color.green); JButton button2 = new JButton("Button2"); button2.setBackground(Color.blue); JButton button3 = new JButton("Button3"); button3.setBackground(Color.magenta); JButton button4 = new JButton("Button4"); button4.setBackground(Color.red); // Setting card layout to JFrame GUI setLayout(cl); add(button1); add(button2); add(button3); add(button4); button1.addActionListener(new ButtonListener()); button2.addActionListener(new ButtonListener()); button3.addActionListener(new ButtonListener()); button4.addActionListener(new ButtonListener()); } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae){ cl.next(panel); } } public static void main(String[] args){ // Create JFrame for GUI frame and title as 'Add Button in JFrame Java Code' CardLayoutTest frame = new CardLayoutTest(); frame.setSize(500,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }Output:
button1:
This java code uses button action listener and event to show all the card layout components.
Shows the button 2 when clicking on button1, similarly button2 click shows button3 and also button3 click shows button4.
Once clicking on button4, buttonn1 will be displayed.
button2:
button3:
button4:
Once executing this java program, Frame with card layout buttons will be popped up as above and closes if we click close button in the frame title.
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page