gpt4 book ai didi

java - 确定选择哪个 JRadioButton 的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-02 09:41:05 24 4
gpt4 key购买 nike

目前,我正在以这种方式获取选定的按钮,但如果这是正确/最好的方法,我不会。也许有比这更简单或更面向对象的东西。

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 本身来实现此目的。即,

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

关于java - 确定选择哪个 JRadioButton 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com