Java:JOptionPane单选按钮

3

我正在编写一个简单的程序来帮助我计算混合电子液所需的材料。我尝试在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");

作为替代方案,考虑使用JComboBox,如Oracle教程所述。 - copeg
我为尼古丁含量提供一个JSpinner(http://forums.aussievapers.com/diy-juice-recipes-mixing/28538-e-juice-mixing-calculator-needs-testing.html),并且它的最高值是**36mg/ml**。 - Andrew Thompson
2个回答

8
作为使用多个 JRadioButton 的替代方案,您可以通过将字符串数组传递给 JOptionPane.showInputDialog 来提供一个选择界面,而不是使用 JComboBox
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");
}

7

您可以创建自定义面板并呈现任何选项,例如:

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);
    }
}

很好的答案,但我如何添加一个与按钮一起的消息? - Nicola Daaboul
1
@NicolaDaaboul 只需在其中添加一个 JLabelpanel.add(new JLabel("我的消息")); - martinez314
太棒了,非常感谢。如果例如选择了button1,我可以这样做吗?如果(button1 == true) {执行一些代码} - Nicola Daaboul
@NicolaDaaboul 添加一个变更监听器。 - Nicholas Eason
1
@NicolaDaaboul,在更改监听器中使用if(button1.isSelected()) - Spikatrix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接