目录

Jython - Menus

大多数基于GUI的应用程序顶部都有一个菜单栏。 它位于顶层窗口的标题栏下方。 javax.swing包具有精心设置的功能来构建高效的菜单系统。 它是在JMenuBar, JMenuJMenuItem类的帮助下构建的。

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

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

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

bar = JMenuBar()
frame.setJMenuBar(bar)

接下来,声明具有“文件”标题的JMenu对象。 “文件”菜单中添加了三个JMenuItem按钮。 单击任何菜单项时,将执行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()

“文件”菜单对象将添加到菜单栏中。 最后,在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口译员
↑回到顶部↑
WIKI教程 @2018