📅  最后修改于: 2020-11-08 07:21:20             🧑  作者: Mango
对话框对象是出现在与用户进行交互的基本窗口顶部的窗口。在本章中,我们将看到在swing库中定义的预配置对话框。它们是MessageDialog,ConfirmDialog和InputDialog 。由于JOptionPane类的静态方法,因此可以使用它们。
在下面的示例中,“文件”菜单具有与上述三个对话框相对应的三个JMenu项;每个执行OnClick事件处理程序。
file = JMenu("File")
msgbtn = JMenuItem("Message",actionPerformed = OnClick)
conbtn = JMenuItem("Confirm",actionPerformed = OnClick)
inputbtn = JMenuItem("Input",actionPerformed = OnClick)
file.add(msgbtn)
file.add(conbtn)
file.add(inputbtn)
OnClick()处理程序函数检索菜单项按钮的标题,并调用相应的showXXXDialog()方法。
def OnClick(event):
str = event.getActionCommand()
if str == 'Message':
JOptionPane.showMessageDialog(frame,"this is a sample message dialog")
if str == "Input":
x = JOptionPane.showInputDialog(frame,"Enter your name")
txt.setText(x)
if str == "Confirm":
s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?")
if s == JOptionPane.YES_OPTION:
txt.setText("YES")
if s == JOptionPane.NO_OPTION:
txt.setText("NO")
if s == JOptionPane.CANCEL_OPTION:
txt.setText("CANCEL")
如果从菜单中选择了消息选项,则会弹出一条消息。如果单击“输入”选项,则会弹出一个对话框,要求输入。输入的文本然后显示在JFrame窗口的文本框中。如果选择了“确认”选项,则会出现一个带有三个按钮“是”,“否”和“取消”的对话框。用户的选择将记录在文本框中。
整个代码如下-
from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField
from java.awt import BorderLayout
from javax.swing import JOptionPane
frame = JFrame("Dialog example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())
def OnClick(event):
str = event.getActionCommand()
if str == 'Message':
JOptionPane.showMessageDialog(frame,"this is a sample message dialog")
if str == "Input":
x = JOptionPane.showInputDialog(frame,"Enter your name")
txt.setText(x)
if str == "Confirm":
s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?")
if s == JOptionPane.YES_OPTION:
txt.setText("YES")
if s == JOptionPane.NO_OPTION:
txt.setText("NO")
if s == JOptionPane.CANCEL_OPTION:
txt.setText("CANCEL")
bar = JMenuBar()
frame.setJMenuBar(bar)
file = JMenu("File")
msgbtn = JMenuItem("Message",actionPerformed = OnClick)
conbtn = JMenuItem("Confirm",actionPerformed = OnClick)
inputbtn = JMenuItem("Input",actionPerformed = OnClick)
file.add(msgbtn)
file.add(conbtn)
file.add(inputbtn)
bar.add(file)
txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)
frame.setVisible(True)
执行上述脚本后,将显示以下窗口,并在菜单中显示三个选项: