0

I'm creating a very simple class to override Swing JRadioButton which allows a user to set a field determining whether or not the radio button is selectable.

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();
    }
}

All of the other methods are implemented. This does not work. When a SelectableRadio button is set as NOT selectable, the radio button is still selected when clicked.

Any help?

4

3 回答 3

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);
}
于 2013-08-06T13:58:25.193 回答
1

您通常将JRadioButtons 放入ButtonGroup.

这是Oracle 教程中的示例。

//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"));
}
于 2013-08-06T14:01:06.690 回答
0

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

于 2013-08-06T14:07:22.493 回答