我有一組 JRadioButtons 的選擇。在這種情況下,它們包含在 ButtonGroup“組”中。
一個按鈕的例子是 reviewrequest = new JRadioButton("request for review"); 等等
我正在嘗試將所選專案轉換為字串: categorystring = group.getSelection().toString(); (為了示例,我們將選擇上面的按鈕)
然而,每當我使用這種方法時,我并沒有得到我想要的 (reviewrequest) 甚至 ("request for review"),而是得到類似這樣的新字串值:
javax.swing.JToggleButton$ToggleButtonModel@482fdd28
有任何想法嗎?謝謝!
uj5u.com熱心網友回復:
問題是ButtonGroup#getSelection()正在回傳現在選擇的 JRadioButton 的 ButtonModel,并且您看到的是public String toString()從該 ButtonModel 物件回傳的,并且此資訊不是非常有用。
為了使您的代碼正常作業,您需要通過呼叫.setActionCommand(...)傳入感興趣的字串來設定 JRadioButtons 的 actionCommand,然后從 ButtonModel 中獲取它:
ButtonModel model = group.getSelection();
// always first check that something is indeed selected
if (model != null) {
categorystring = model.getActionCommand();
}
例如:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
@SuppressWarnings("serial")
public class ButtonModelExample extends JPanel {
private static final String[] BUTTON_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
private JTextField resultField = new JTextField(10);
public ButtonModelExample() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
resultField.setFocusable(false);
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
for (String buttonText : BUTTON_TEXTS) {
JRadioButton radioBtn = new JRadioButton(buttonText);
radioBtn.setActionCommand(buttonText);
radioBtn.addChangeListener(cl -> {
ButtonModel buttonModel = buttonGroup.getSelection();
if (buttonModel != null) {
String text = buttonModel.getActionCommand();
resultField.setText(text);
}
});
radioPanel.add(radioBtn);
buttonGroup.add(radioBtn);
}
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(radioPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ButtonModelExample mainPanel = new ButtonModelExample();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/526170.html
