当我在Java Swing中选择JRadioButton时,如何在弹出窗口中创建JTextFields

时间:2016-02-19 00:57:20

标签: java swing

我是Java Swing的新手。

当我选择一个JRadioButton时,它应弹出JTextFields,用户可以在其中输入姓名,年龄等详细信息。如果有任何问题,请告诉我。

任何人都可以帮我解决以下示例代码吗?

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class DialogTest extends JDialog implements ActionListener {

    private static final String TITLE = "Season Test";

    private enum Season {
        WINTER("Winter"), SPRING("Spring");
        private JRadioButton button;
        private Season(String title) {
            this.button = new JRadioButton(title);
        }
    }

    private DialogTest(JFrame frame, String title) {
        super(frame, title);
        JPanel radioPanel = new JPanel();
        radioPanel.setSize(800,800);
        radioPanel.setLayout(new GridLayout(3, 1));
        ButtonGroup group = new ButtonGroup();

        for (Season s : Season.values()) {
            group.add(s.button);
            radioPanel.add(s.button);
            s.button.addActionListener(this);
        }
        Season.SPRING.button.setSelected(true);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.add(radioPanel);
        this.pack();
        this.setLocationRelativeTo(frame);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JRadioButton b = (JRadioButton) e.getSource();
        JOptionPane.showMessageDialog(null, "You chose: " + b.getText());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new DialogTest(null, TITLE);
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

从它的声音中,你想要一个"模态"对话。有关详细信息,请参阅How to Make Dialogs

您还可以使用CardLayout在按钮选择更改时显示更多详细信息,有关详细信息,请参阅How to Use CardLayout