Custom JMenuItems in Java

后端 未结 3 909
刺人心
刺人心 2020-12-30 07:22

Would it be possible to create a custom JMenuItem that contains buttons? For example would it be possible to create a JMenuITem with an item simila

3条回答
  •  -上瘾入骨i
    2020-12-30 08:16

    I doubt there is an easy way to do this. You can do something like:

    JMenuItem item = new JMenuItem("Edit                       ");
    item.setLayout( new FlowLayout(FlowLayout.RIGHT, 5, 0) );
    JButton copy = new JButton("Copy");
    copy.setMargin(new Insets(0, 2, 0, 2) );
    item.add( copy );
    menu.add( item );
    

    But there are several problems:

    a) the menu doesn't close when you click on the button. So that code would need to be added to your ActionListener

    b) the menu item doesn't respond to key events like the left/right arrow, so there is no way to place focus on the button using the keyboard. This would involve UI changes to the menu item and I have no idea where to start for this.

    I would just use the standard UI design an create sub menus.

提交回复
热议问题