2013-08-06 25 views
0

我創建了一個非常簡單的類來覆蓋Swing JRadioButton,它允許用戶設置字段來確定單選按鈕是否可選。如何消耗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按鈕被設置爲不可選時,單擊時單選按鈕仍然被選中。

任何幫助?

+0

你爲什麼要混淆你的用戶? – kleopatra

+0

如果它不可選,每次調用'setSelection(false)'。 – GGrec

+0

或者,爲避免讓用戶感到困惑,正如kleopatra所說,請直接禁用按鈕。 – GGrec

回答

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

這實際上是我在找的東西。謝謝回答我的問題。 – jiveturkey

1

你通常把JRadioButton s轉換爲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")); 
} 
0

您是否試過jRadioButton的啓用屬性?它使其可選或不可選。