新彩天欢迎您!
幻海优品

Jython - 菜单

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

在下面的示例中,提供了一个菜单栏.顶级窗口.菜单栏中添加了一个由三个菜单项按钮组成的文件菜单.现在让我们准备一个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按钮添加到"文件"菜单中.单击任何菜单项时,将执行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, JTextFieldfrom java.awt import BorderLayoutframe = 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 Interpreter

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除