Jython - 菜单


大多数基于 GUI 的应用程序在顶部都有一个菜单栏。它位于顶级窗口的标题栏正下方。javax.swing 包具有构建高效菜单系统的精心设计工具。它是在 JMenuBar、JMenu 和 JMenuItem 类的帮助下构建的。

在以下示例中,顶级窗口中提供了一个菜单栏。由三个菜单项按钮组成的 File 菜单将添加到菜单栏中。现在,让我们准备一个 JFrame 对象,并将布局设置为 BorderLayout。


frame = JFrame("JMenuBar example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

现在,JMenuBar 对象由 SetJMenuBar() 方法激活。


bar = JMenuBar()
frame.setJMenuBar(bar)

接下来,声明具有 'File' 标题的 JMenu 对象。三个 JMenuItem 按钮被添加到 File 菜单中。单击任何菜单项时,将执行 ActionEvent 处理程序 OnClick() 函数。它是使用 actionPerformed 属性定义的。


file = JMenu("File")
newfile = JMenuItem("New",actionPerformed = OnClick)
openfile = JMenuItem("Open",actionPerformed = OnClick)
savefile = JMenuItem("Save",actionPerformed = OnClick)
file.add(newfile)
file.add(openfile)
file.add(savefile)
bar.add(file)

OnClick() 事件处理程序通过 gwtActionCommand() 函数检索 JMenuItem 按钮的名称,并将其显示在窗口底部的文本框中。


def OnClick(event):
	 	txt.text = event.getActionCommand()

File (文件) 菜单对象被添加到菜单栏中。最后,在 JFrame 对象的底部添加一个 JTextField 控件。


txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)

menu.py 的整个代码如下 -


from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField
from java.awt import BorderLayout

frame = JFrame("JMenuBar example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

def OnClick(event):
	 	txt.text = event.getActionCommand()

bar = JMenuBar()
frame.setJMenuBar(bar)

file = JMenu("File")
newfile = JMenuItem("New",actionPerformed = OnClick)
openfile = JMenuItem("Open",actionPerformed = OnClick)
savefile = JMenuItem("Save",actionPerformed = OnClick)
file.add(newfile)
file.add(openfile)
file.add(savefile)
bar.add(file)

txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)

frame.setVisible(True)

使用 Jython 解释器执行上述脚本时,将出现一个带有 File 菜单的窗口。单击它,它的三个菜单项将下拉。如果单击任何按钮,其名称将显示在文本框控件中。

Jython 解释器