如何获取所选JRadioButton的字符串或值?

时间:2014-05-04 12:40:37

标签: java

我正在尝试创建一个程序,该程序将从用户那里获取一些信息并存储它。到目前为止一切顺利,但现在我发现自己无法从一组单选按钮中收集字符串或值。

我希望用户选择我的程序的按钮将从中获取字符串。 我刚刚开始使用Java,所以如果有人可以帮助我,我会感到很兴奋。

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Lab_11_1_Question_1 extends JFrame
{
    private JLabel text1 = new JLabel("Name: ");
    private JLabel text2 = new JLabel("Surname: ");
    private JLabel text3 = new JLabel("Departament: ");
    private JLabel text4 = new JLabel("Gender: ");
    private JTextField textfield1 = new JTextField(10);
    private JTextField textfield2 = new JTextField(10);
    private JRadioButton radio1 = new JRadioButton("Female");
    private JRadioButton radio2 = new JRadioButton("Male");
    private JComboBox<String> box1 = new JComboBox<String>(new String[]
    { "Computer Engineering", "Civil Engineering", "Mining Engineering" });
    private JButton button1 = new JButton("List");
    private JButton button2 = new JButton("Add");

    Lab_11_1_Question_1()
    {
        super("Manage Students");
        setLayout(new GridLayout(5, 2, 5, 5));
        add(text1);
        add(textfield1);
        add(text2);
        add(textfield2);
        add(text3);
        add(box1);
        add(text4);
        ButtonGroup group1 = new ButtonGroup();
        group1.add(radio1);
        group1.add(radio2);
        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(1, 2, 5, 5));
        panel1.add(radio1);
        panel1.add(radio2);
        add(panel1);
        add(button1);
        add(button2);

        MyClass listener = new MyClass();

        button1.addActionListener(listener);
        button2.addActionListener(listener);
    }

    public class MyClass implements ActionListener
    {

        public void actionPerformed(ActionEvent e)
        {

            if (e.getSource() == button2)
            {
                String name = textfield1.getText();
                String surname = textfield2.getText();
                String departament = (String) (box1.getSelectedItem());
            }

        }

    }

    public static void main(String[] arg)
    {
        Lab_11_1_Question_1 frame = new Lab_11_1_Question_1();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();

    }

}

1 个答案:

答案 0 :(得分:2)

radio1.getText()怎么样?

此方法在javax.swing.AbstractButton中声明。有关详细信息,请参阅Java文档:JRadioButtonAbstractButton