您可以創建一個按鈕組這樣的:
public class SingleSelectionButtonGroup {
private final List<JButton> buttons;
public static SingleSelectionButtonGroup group(List<JButton> buttons) {
return new SingleSelectionButtonGroup(buttons);
}
public static SingleSelectionButtonGroup group(JButton...buttons) {
return new SingleSelectionButtonGroup(Arrays.asList(buttons));
}
private SingleSelectionButtonGroup(List<JButton> buttons) {
this.buttons = new ArrayList<JButton>(buttons);
setupListener();
}
private void setupListener() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
SingleSelectionButtonGroup.this.disableAllExcept((JButton) e.getSource());
}
};
for (JButton button : buttons) {
button.addActionListener(listener);
}
}
private void disableAllExcept(JButton clickedButton) {
for (JButton button : buttons) {
if (!clickedButton.equals(button)) {
button.setEnabled(false);
}
}
}
}
然後用按鈕集合使用它要組:
public class Application {
public void run() {
final JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 300));
final JPanel pane = new JPanel();
List<JButton> buttons = new ArrayList<JButton>();
String[] texts = {"A", "B", "C"};
for (String text : texts) {
JButton button = new JButton(text);
buttons.add(button);
pane.add(button);
}
SingleSelectionButtonGroup.group(buttons);
frame.getContentPane().add(pane);
frame.setVisible(true);
}
public static void main(String[] args) {
new Application().run();
}
}
你的按鈕是否有任何'ActionListener'?你想讓用戶點擊按鈕,什麼都沒有發生,或者用戶不能點擊按鈕? – Genzer 2013-04-04 14:36:56
你想只消耗()mouseevents ???,但是事件來自KeyBoard(Enter和Tab被實現爲加速器) – mKorbel 2013-04-04 14:54:52
不,這絕對不是你應該想要的:一個行爲良好的用戶界面必須是平等的鍵盤_和_鼠標可以很好地使用。你的_real_目標是什麼? – kleopatra 2013-04-04 15:18:25