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

JOptionPane ใน Java มีกล่องโต้ตอบ (Dialog) กี่ประเภท?

JOptionPane เป็นคลาสย่อยของ JComponent ที่มีเมธอดสแตติกสำหรับสร้างและปรับแต่ง กล่องโต้ตอบแบบโมดอล (modal dialog) ด้วยโค้ดที่เรียบง่าย ใช้แทน JDialog เพื่อลดความซับซ้อนของโค้ด JOptionPane แสดงกล่องโต้ตอบพร้อมไอคอนมาตรฐาน 4 แบบ (คำถาม, ข้อมูล, คำเตือน, และข้อผิดพลาด) หรือไอคอนที่ผู้ใช้กำหนดเอง

ประเภทของกล่องโต้ตอบ 4 แบบ

  • MessageDialog - แสดงข้อความ พร้อมเพิ่มไอคอนเพื่อแจ้งเตือนผู้ใช้
  • ConfirmDialog - แสดงข้อความและให้ผู้ใช้ตอบคำถาม (ใช่/ไม่/ยกเลิก)
  • InputDialog - แสดงข้อความและอนุญาตให้ผู้ใช้ป้อนข้อความ
  • OptionDialog - ครอบคลุมทั้ง 3 ประเภทข้างต้น ทำให้ปรับแต่งได้อย่างเต็มที่

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

import javax.swing.*;

public class JoptionPaneTest {
    public static void main(String[] args) {
        JFrame frame = new JFrame("JoptionPane Test");
        frame.setSize(200, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        // MessageDialog แบบง่าย
        JOptionPane.showMessageDialog(frame, "Hello Java");

        // MessageDialog พร้อมไอคอนเตือนและหัวข้อ
        JOptionPane.showMessageDialog(frame,
            "You have less amount, please recharge",
            "Apocalyptic message",
            JOptionPane.WARNING_MESSAGE);

        // ConfirmDialog
        int result = JOptionPane.showConfirmDialog(null,
            "Do you want to remove item now?");

        switch (result) {
            case JOptionPane.YES_OPTION:
                System.out.println("Yes");
                break;
            case JOptionPane.NO_OPTION:
                System.out.println("No");
                break;
            case JOptionPane.CANCEL_OPTION:
                System.out.println("Cancel");
                break;
            case JOptionPane.CLOSED_OPTION:
                System.out.println("Closed");
                break;
        }

        // InputDialog
        String name = JOptionPane.showInputDialog(null, "Please enter your name.");
        System.out.println(name);

        // OptionDialog แบบกำหนดเอง (Login)
        JTextField userField = new JTextField();
        JPasswordField passField = new JPasswordField();
        String message = "Please enter your user name and password.";
        result = JOptionPane.showOptionDialog(frame,
            new Object[] {message, userField, passField},
            "Login",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null, null, null);

        if (result == JOptionPane.OK_OPTION)
            System.out.println(userField.getText() + " " + new String(passField.getPassword()));

        System.exit(0);
    }
}

ผลลัพธ์

โปรแกรมจะแสดงกล่องโต้ตอบตามลำดับ: กล่องข้อความธรรมดา, กล่องเตือน, กล่องยืนยัน, กล่องป้อนข้อความ, และกล่องล็อกอินแบบกำหนดเอง