我想将2个JRadioButtonMenuItem作为子菜单项添加到JMenuItem,但是子菜单项无法正确显示。

这是我到目前为止尝试过的代码

 private void setupEditMenu() {

    editMenu = new JMenu("Edit");

    // some code..

    tabSpaceMenuItem = new JMenuItem("Tab Length");
    editMenu.add(tabSpaceMenuItem);

    ButtonGroup tabSpaceButtonGroup = new ButtonGroup();
    JMenuItem fourSpacedTabMenuItem, eightSpacedTabMenuItem;

    fourSpacedTabMenuItem = new JRadioButtonMenuItem("4 spaces");
    fourSpacedTabMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            editor.setTabSize(4);
        }
    });
    tabSpaceButtonGroup.add(fourSpacedTabMenuItem);
    tabSpaceMenuItem.add(fourSpacedTabMenuItem);

    eightSpacedTabMenuItem = new JRadioButtonMenuItem("8 spaces");
    eightSpacedTabMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            editor.setTabSize(8);
        }
    });
    tabSpaceButtonGroup.add(eightSpacedTabMenuItem);
    tabSpaceMenuItem.add(eightSpacedTabMenuItem);

    if(editor.getTabSize() == 4)
        fourSpacedTabMenuItem.setSelected(true);
    if(editor.getTabSize() == 8) {
        eightSpacedTabMenuItem.setSelected(true);
    }
}


电流输出
java - JMenu子菜单项无法正确显示-LMLPHP

预期:

Edit
 |-Find
 |-Font
 |-Tab Length
    |- 4 spaces
    |- 8 spaces


我想念什么?

最佳答案

JMenuItem不是其他JMenuItem的容器。而是将tabSpaceMenuItem更改为JMenu ...

tabSpaceMenuItem = new JMenu("Tab Length");


java - JMenu子菜单项无法正确显示-LMLPHP

07-24 09:23