📄 Description

Quand on parle de CardLayout, on fait souvent rĂ©fĂ©rence Ă  une fenĂȘtre avec des onglets permettant d’accĂ©der Ă  des sous pages.

image.png

📚 Documentation

Documentation CardLayout

✅ RĂ©sultat

image.png

image.png

đŸ–„ïž Code CardLayoutTest.java

Ce code n’utilise pas le layout CardLayout mais permet d’avoir une fenĂȘtre avec onglets. De plus, c’est facilement utilisable avec WindowBuilder.

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Color;

public class CardLayoutTest {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CardLayoutTest window = new CardLayoutTest();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public CardLayoutTest() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("(CardLayout)");
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(0, 0, 436, 263);
		frame.getContentPane().add(tabbedPane);
		
		JPanel onglet_1 = new JPanel();
		onglet_1.setBackground(new Color(0, 255, 64));
		tabbedPane.addTab("Titre 1", null, onglet_1, null);
		onglet_1.setLayout(null);
		
		JLabel lblPage1 = new JLabel("Page 1");
		lblPage1.setBackground(new Color(0, 0, 0));
		lblPage1.setHorizontalAlignment(SwingConstants.CENTER);
		lblPage1.setBounds(150, 90, 123, 38);
		onglet_1.add(lblPage1);
		
		JPanel onglet_2 = new JPanel();
		onglet_2.setBackground(new Color(0, 255, 255));
		onglet_2.setLayout(null);
		tabbedPane.addTab("Titre 2", null, onglet_2, null);
		
		JLabel lblPage2 = new JLabel("Page 2");
		lblPage2.setHorizontalAlignment(SwingConstants.CENTER);
		lblPage2.setBounds(150, 90, 123, 38);
		onglet_2.add(lblPage2);
	}
}

✏ Etapes

  1. CrĂ©er une fenĂȘtre WindowBuilder
  2. Ouvrir WindowBuilder
  3. Changer le layout du ContentPane