繁体   English   中英

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

[英]How to get the String or Value of a selected JRadioButton?

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

我希望用户选择我的程序的按钮将从中获取字符串。 我刚开始使用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();

    }

}

radio1.getText()呢?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM