Java:JOptionPane 单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30265720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:47:25  来源:igfitidea点击:

Java: JOptionPane Radio Buttons

javaswingbuttoninputjoptionpane

提问by Nicola Daaboul

I'm working on a simple program to help me calculate stuff for mixing eLiquid. I am trying to add radio buttons within JOptionPane.showInputDialog but I can't link them together. When I run the program, nothing comes up. This is all I have:

我正在开发一个简单的程序来帮助我计算用于混合 eLiquid 的东西。我正在尝试在 JOptionPane.showInputDialog 中添加单选按钮,但我无法将它们链接在一起。当我运行程序时,什么也没有出现。这就是我所拥有的:

JRadioButton nicSelect = new JRadioButton("What is the target Nicotine level? ");
        JRadioButton b1 = new JRadioButton("0");
        JRadioButton b2 = new JRadioButton("3");
        JRadioButton b3 = new JRadioButton("6");
        JRadioButton b4 = new JRadioButton("12");
        JRadioButton b5 = new JRadioButton("18");
        JRadioButton b6 = new JRadioButton("24");

回答by copeg

As an alternative to using several JRadioButton's, you can provide a selection interface via a JComboBoxby passing a String array to the JOptionPane.showInputDialog:

作为使用多个的替代方法JRadioButton,您可以JComboBox通过将字符串数组传递给 JOptionPane.showInputDialog来提供选择界面:

String[] values = {"0", "3", "6", "12", "18", "24"};

Object selected = JOptionPane.showInputDialog(null, "What is the target Nicotine level?", "Selection", JOptionPane.DEFAULT_OPTION, null, values, "0");
if ( selected != null ){//null if the user cancels. 
    String selectedString = selected.toString();
    //do something
}else{
    System.out.println("User cancelled");
}

回答by whiskeyspider

You can create a custom panel and present any options you like, for example:

您可以创建自定义面板并显示您喜欢的任何选项,例如:

public class Test {

    public static void main(final String[] args) {
        final JPanel panel = new JPanel();
        final JRadioButton button1 = new JRadioButton("1");
        final JRadioButton button2 = new JRadioButton("2");

        panel.add(button1);
        panel.add(button2);

        JOptionPane.showMessageDialog(null, panel);
    }
}