溫馨提示×

如何在java中實現(xiàn)showdialog

小樊
81
2024-09-29 12:02:02
欄目: 編程語言

在Java中,您可以使用JDialog類來創(chuàng)建一個對話框。以下是一個簡單的示例,展示了如何創(chuàng)建一個帶有“確定”和“取消”按鈕的對話框:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShowDialogExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> showDialog());
    }

    private static void showDialog() {
        // 創(chuàng)建一個新的JDialog實例
        JDialog dialog = new JDialog();
        dialog.setTitle("示例對話框");
        dialog.setSize(300, 200);
        dialog.setLocationRelativeTo(null); // 居中顯示
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        // 創(chuàng)建一個容器(JPanel)來存放對話框中的組件
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new GridLayout(2, 1));

        // 創(chuàng)建一個標簽
        JLabel label = new JLabel("請選擇一個選項:");
        contentPane.add(label);

        // 創(chuàng)建一個按鈕組,包含“確定”和“取消”按鈕
        JButton[] buttons = new JButton[2];
        buttons[0] = new JButton("確定");
        buttons[1] = new JButton("取消");

        // 為“確定”按鈕添加點擊事件監(jiān)聽器
        buttons[0].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedOption = "確定";
                JOptionPane.showMessageDialog(dialog, selectedOption);
                dialog.dispose();
            }
        });

        // 為“取消”按鈕添加點擊事件監(jiān)聽器
        buttons[1].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedOption = "取消";
                JOptionPane.showMessageDialog(dialog, selectedOption);
                dialog.dispose();
            }
        });

        contentPane.add(buttons[0]);
        contentPane.add(buttons[1]);

        // 將容器添加到對話框中
        dialog.setContentPane(contentPane);

        // 顯示對話框
        dialog.setVisible(true);
    }
}

這個示例創(chuàng)建了一個簡單的對話框,包含“確定”和“取消”按鈕。當用戶點擊這些按鈕時,將顯示一個JOptionPane,其中包含按鈕的名稱。然后,對話框?qū)㈥P閉。

0