Jython - 对话框



对话框对象是一个显示在与其交互的基础窗口顶部的窗口。在本章中,我们将了解在 Swing 库中定义的预配置对话框。它们是 MessageDialog、ConfirmDialogInputDialog。它们可以通过 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)

执行上述脚本时,将显示以下窗口,菜单中有三个选项 −

Dialog

消息框

Message box

输入框

Input Box

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

确认对话框

Confirm Dialog
广告