如何在鼠标单击时使用JRadioButton选择似乎不起作用

时间:2013-08-06 13:54:22

标签: java swing jradiobutton mouse-listeners buttongroup

我正在创建一个非常简单的类来覆盖Swing JRadioButton,它允许用户设置一个字段来确定单选按钮是否可选。

public class SelectableRadio extends JRadioButton implements MouseListener
private boolean selectable = true;
public SelectableRadio()
{
    super();
    addMouseListener(this);
}

public void setSelectable(boolean select)
{
    selectable = select;
}

@Override
public void mousePressed(MouseEvent e)
{
    if (!selectable)
    {
        e.consume();
    }
}

所有其他方法都已实施。这不起作用。当SelectableRadio按钮设置为NOT selectable时,单击时仍然会选中单选按钮。

任何帮助?

3 个答案:

答案 0 :(得分:2)

您需要更改setSelectable代码,并添加以下内容:

if (editable) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    super.enableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
} else {
    this.setCursor(CursorFactory.createUnavailableCursor());
    super.disableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
}

答案 1 :(得分:1)

您通常会将JRadioButton放入ButtonGroup

以下是Oracle tutorial的示例。

//Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);

JRadioButton dogButton = new JRadioButton(dogString);
dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);

JRadioButton rabbitButton = new JRadioButton(rabbitString);
rabbitButton.setMnemonic(KeyEvent.VK_R);
rabbitButton.setActionCommand(rabbitString);

JRadioButton pigButton = new JRadioButton(pigString);
pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);

//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);

//Register a listener for the radio buttons.
birdButton.addActionListener(this);
catButton.addActionListener(this);
dogButton.addActionListener(this);
rabbitButton.addActionListener(this);
pigButton.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
    picture.setIcon(new ImageIcon("images/" 
                              + e.getActionCommand() 
                              + ".gif"));
}

答案 2 :(得分:0)

您是否尝试过jRadioButton的启用属性?它使其可选择或不可选择。