- Jython 教程
- Jython - 主页
- Jython - 概述
- Jython - 安装
- Jython - 导入 Java 库
- Jython - 变量和数据类型
- Jython - 使用 Java 集合类型
- Jython - 决策控制
- Jython - 循环
- Jython - 函数
- Jython - 模块
- Jython - 包
- Jython - Java 应用程序
- Jython - Eclipse 插件
- Jython - Eclipse 中的项目
- Jython - NetBeans 插件和项目
- Jython - Servlet
- Jython-JDBC
- Jython - 使用 Swing GUI 库
- Jython - 布局管理
- Jython - 事件处理
- Jython - 菜单
- Jython - 对话框
- Jython 有用资源
- Jython - 快速指南
- Jython - 有用的资源
- Jython - 讨论
Jython - 对话框
Dialog 对象是出现在用户与之交互的基本窗口顶部的窗口。在本章中,我们将看到 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)
执行上述脚本时,将显示以下窗口,菜单中包含三个选项 -
留言框
输入框
确认对话框
