如何自定義java中的showdialog

小樊
81
2024-09-29 12:04:03

在Java中,要自定義一個(gè)JDialog,您需要擴(kuò)展JDialog類并重寫(xiě)相關(guān)方法。以下是一個(gè)簡(jiǎn)單的示例,展示了如何創(chuàng)建一個(gè)自定義的JDialog

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

public class CustomJDialog extends JDialog {

    public CustomJDialog(Frame owner, String title) {
        super(owner, title, true);
        setSize(300, 200);
        setLocationRelativeTo(owner);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        initComponents();
    }

    private void initComponents() {
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());

        JLabel label = new JLabel("這是一個(gè)自定義對(duì)話框");
        contentPane.add(label, BorderLayout.CENTER);

        JButton closeButton = new JButton("關(guān)閉");
        contentPane.add(closeButton, BorderLayout.SOUTH);

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("自定義對(duì)話框示例");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(400, 300);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                CustomJDialog customDialog = new CustomJDialog(frame, "自定義對(duì)話框");
                customDialog.setVisible(true);
            }
        });
    }
}

在這個(gè)示例中,我們創(chuàng)建了一個(gè)名為CustomJDialog的類,它擴(kuò)展了JDialog。我們?cè)跇?gòu)造函數(shù)中設(shè)置了對(duì)話框的所有權(quán)、標(biāo)題、大小、位置和關(guān)閉操作。然后,我們調(diào)用initComponents()方法來(lái)初始化對(duì)話框的組件,如標(biāo)簽和按鈕。

initComponents()方法中,我們創(chuàng)建了一個(gè)JPanel作為內(nèi)容面板,并設(shè)置了其布局。然后,我們添加了一個(gè)標(biāo)簽和一個(gè)按鈕到內(nèi)容面板上。最后,我們?yōu)榘粹o添加了一個(gè)ActionListener,當(dāng)用戶點(diǎn)擊按鈕時(shí),對(duì)話框?qū)㈥P(guān)閉。

main()方法中,我們創(chuàng)建了一個(gè)JFrame和一個(gè)CustomJDialog實(shí)例,并分別設(shè)置它們的可見(jiàn)性。這樣,當(dāng)您運(yùn)行程序時(shí),您將看到一個(gè)包含自定義對(duì)話框的窗口。

0