gpt4 book ai didi

java - 协调两个 `ButtonGroup`

转载 作者:行者123 更新时间:2023-11-29 06:02:10 24 4
gpt4 key购买 nike

我在菜单中有一组 3 个 JRadioButtonMenuItem,在工具栏中有 3 个 JToggleButton。它们中的每一个都绑定(bind)到 3 个 Action,因此当我禁用一个操作时,相应的项目和按钮都将被禁用。

当我点击一个菜单项时,我希望相应的工具栏按钮也被选中,但似乎“未点击”组对这些事件有其自己奇怪的 react 方式(我没有采用一种模式尝试识别)。

这是菜单组代码(简化):

ButtonGroup menuGrp = new ButtonGroup();

JRadioButtonMenuItem itemA = new JRadioButtonMenuItem(actionA);
JRadioButtonMenuItem itemB = new JRadioButtonMenuItem(actionB);
JRadioButtonMenuItem itemC = new JRadioButtonMenuItem(actionC);

menuGrp.add(itemA);
menuGrp.add(itemB);
menuGrp.add(itemC);

itemA.setSelected(true);

这里是工具栏组代码:

ButtonGroup toolbarGrp = new ButtonGroup();

JToggleButton buttonA = new JToggleButton(actionA);
JToggleButton buttonB = new JToggleButton(actionB);
JToggleButton buttonC = new JToggleButton(actionC);

toolbarGrp.add(buttonA);
toolbarGrp.add(buttonB);
toolbarGrp.add(buttonB);

buttonA.setSelected(true);

最佳答案

我不知道你到底是怎么做到的,但这段代码对我有用:

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToggleButton;


public class Button
{
public static void main(String[] args){
JFrame frame = new JFrame();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Foo");

ButtonGroup menuGrp = new ButtonGroup();
JRadioButtonMenuItem itemA = new JRadioButtonMenuItem();
JRadioButtonMenuItem itemB = new JRadioButtonMenuItem();
JRadioButtonMenuItem itemC = new JRadioButtonMenuItem();
menuGrp.add(itemA);
menuGrp.add(itemB);
menuGrp.add(itemC);
menu.add(itemA);
menu.add(itemB);
menu.add(itemC);
itemA.setSelected(true);

bar.add(menu);
frame.setJMenuBar(bar);

JPanel content = new JPanel();

ButtonGroup toolbarGrp = new ButtonGroup();
JToggleButton buttonA = new JToggleButton();
JToggleButton buttonB = new JToggleButton();
JToggleButton buttonC = new JToggleButton();
toolbarGrp.add(buttonA);
toolbarGrp.add(buttonB);
toolbarGrp.add(buttonC);
buttonA.setSelected(true);

content.add(buttonA);
content.add(buttonB);
content.add(buttonC);

itemA.setAction(new MyAction(buttonA));
itemB.setAction(new MyAction(buttonB));
itemC.setAction(new MyAction(buttonC));
buttonA.setAction(new MyAction(itemA));
buttonB.setAction(new MyAction(itemB));
buttonC.setAction(new MyAction(itemC));
frame.setContentPane(content);
frame.setSize(300, 300);
frame.setVisible(true);
}

static class MyAction extends AbstractAction
{
AbstractButton button;

public MyAction(AbstractButton button){
this.button = button;
}

@Override public void actionPerformed(ActionEvent e){
button.setSelected(true);
}


}
}

关于java - 协调两个 `ButtonGroup`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9712162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com