目前我正在以这种方式获取选定的按钮,但如果这是正确/最好的方法,我不会。也许有比这更简单或更面向对象的东西。
private int getFilterType(JRadioButton... buttons) {
for (int i = 0, n = buttons.length; i < n; i++) {
if (buttons[i].isSelected()) {
return i + 1;
}
}
return buttons.length + 1;
}
我喜欢使用 ButtonGroup 本身来实现此目的。 IE。,
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ButtonModelEg {
public static final String[] BUTTON_TEXTS = {"Fe", "Fi", "Fo", "Fum"};
private static void createAndShowUI() {
final ButtonGroup btnGroup = new ButtonGroup();
JPanel panel = new JPanel(new GridLayout(0, 1));
for (String btnText : BUTTON_TEXTS) {
JRadioButton radioBtn = new JRadioButton(btnText);
radioBtn.setActionCommand(btnText);
btnGroup.add(radioBtn);
panel.add(radioBtn);
}
final JTextField selectionField = new JTextField();
JButton button = new JButton(new AbstractAction("Get Choice"){
public void actionPerformed(ActionEvent arg0) {
// get the button model selected from the button group
ButtonModel selectedModel = btnGroup.getSelection();
if (selectedModel != null) {
// and dislay it
selectionField.setText(selectedModel.getActionCommand());
}
}
});
panel.add(button);
panel.add(selectionField);
JFrame frame = new JFrame("ButtonModelEg");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)