Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของคลาส CardLayout ใน Java

การทำงานของ CardLayout จัดเรียงคอมโพเนนต์แบบลำดับ และ เห็นได้เพียงคอมโพเนนต์เดียวในเวลาเดียวกัน แต่ละคอมโพเนนต์ถือเป็นการ์ดหนึ่งใบ

CardLayout

  • CardLayout ต่างจาก Layout อื่นๆ ที่พยายามแสดงทุกคอมโพเนนต์พร้อมกัน CardLayout แสดงเพียงหนึ่งคอมโพเนนต์ในเวลาเดียวกัน
  • ใน CardLayout การ์ดมักวางในคอนเทนเนอร์อย่าง JPanel คอมโพเนนต์เข้าคิวตามลำดับที่เพิ่ม
  • เมธอดสำคัญ: first(), last(), next(), previous(), show()

ตัวอย่างโค้ด

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);
    }
}

ในตัวอย่าง ใช้ CardLayout ที่เห็นได้แค่คอมโพเนนต์เดียว (Java) คลิกหน้าต่างจะสลับไป Python และ Scala

ผลลัพธ์

ความสำคัญของคลาส CardLayout ใน Java