📜  Jython-菜单

📅  最后修改于: 2020-11-08 07:21:00             🧑  作者: Mango


大多数基于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口译员