Jython 简明教程

Jython - Dialogs

Dialog 对象是一个窗口,出现在用户与其进行交互的基础窗口的顶部。在本章中,我们将看到 Swing 库中定义的预配置对话框。它们是 MessageDialog, ConfirmDialogInputDialog 。它们是由于 JOptionPane 类的静态方法而可以使用。

在以下示例中,File 菜单包含三个 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

message box

Input Box

input box

Confirm Dialog

confirm dialog