在Java中,JDialog
是一個(gè)對(duì)話框類,用于創(chuàng)建模態(tài)或非模態(tài)對(duì)話框。showDialog()
方法是JDialog
類的一個(gè)實(shí)例方法,用于顯示對(duì)話框并阻塞當(dāng)前線程直到用戶關(guān)閉它。以下是一個(gè)簡(jiǎn)單的示例,演示如何使用JDialog
和showDialog()
方法創(chuàng)建一個(gè)簡(jiǎn)單的模態(tài)對(duì)話框:
import javax.swing.*;
import java.awt.*;
public class ShowDialogExample {
public static void main(String[] args) {
// 創(chuàng)建一個(gè)JFrame作為對(duì)話框的父窗口
JFrame frame = new JFrame("Show Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
// 創(chuàng)建一個(gè)JButton,用于觸發(fā)對(duì)話框的顯示
JButton button = new JButton("Show Dialog");
frame.add(button);
// 為按鈕添加點(diǎn)擊事件監(jiān)聽(tīng)器
button.addActionListener(e -> {
// 創(chuàng)建一個(gè)JDialog實(shí)例
JDialog dialog = new JDialog(frame, "Modal Dialog", true);
// 設(shè)置對(duì)話框的大小
dialog.setSize(200, 100);
// 設(shè)置對(duì)話框的布局
dialog.setLayout(new FlowLayout());
// 創(chuàng)建一個(gè)JLabel,用于顯示對(duì)話框中的文本
JLabel label = new JLabel("This is a modal dialog.");
dialog.add(label);
// 顯示對(duì)話框
dialog.showDialog();
});
// 顯示父窗口
frame.setVisible(true);
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)包含按鈕的簡(jiǎn)單JFrame
。當(dāng)用戶點(diǎn)擊按鈕時(shí),將顯示一個(gè)包含文本標(biāo)簽的模態(tài)對(duì)話框。showDialog()
方法將阻塞當(dāng)前線程,直到用戶關(guān)閉對(duì)話框。