【问题标题】:How to set variables to equal what the user inputs into a JDialog?如何将变量设置为等于用户输入到 JDialog 中的内容?
【发布时间】:2013-11-09 11:33:34
【问题描述】:

所以我试图从 JDialog 中获取用户的输入,这是 JDialog 中的代码:

public void addPipeUI(){
     Integer[] grade = {1,2,3,4,5};
     Integer[] colour = {0, 1, 2};
     float length;
     int diameter;
     boolean chemResist, innerIns, outerRein;
     GridLayout gridLayout = new GridLayout(0,2);

     JDialog dialog = new JDialog();
     dialog.setSize(400, 400);
     dialog.setLocation(250, 250);
     dialog.setTitle("Add Pipe");
     dialog.setLayout(gridLayout);
     dialog.setVisible(true);

     dialog.add(new JLabel("Grade"));
     JComboBox gradeField = new JComboBox(grade);
     dialog.add(gradeField);

     dialog.add(new JLabel("Colour"));
     JComboBox colourField = new JComboBox(colour);
     dialog.add(colourField);

     dialog.add(new JLabel("Length (Meters)"));
     JTextField lengthField = new JTextField();
     dialog.add(lengthField);

     dialog.add(new JLabel("Diameter (Inches)"));
     JTextField diameterField = new JTextField();
     dialog.add(diameterField);

     JRadioButton innerInsField = new JRadioButton("Inner Insluation");
     dialog.add(innerInsField);

     JRadioButton outerReinField = new JRadioButton("Outer Reinforcement");
     dialog.add(outerReinField);

     JRadioButton chemResistField = new JRadioButton("Chemical Resistance");
     dialog.add(chemResistField);

     JButton ok = new JButton("OK");
     dialog.add(ok);


 }

在顶部你可以看到我希望用户输入什么信息。

当按下 OK 按钮时,我想让局部变量等于用户输入的内容,然后将这些变量返回给我的 Main 类进行处理。 我觉得我需要在 OK 按钮上设置一个动作监听器,但是当我这样做时,不能使用局部变量,现在我很困惑。如何使局部变量等于用户输入的内容?

【问题讨论】:

    标签: java swing actionlistener jdialog


    【解决方案1】:

    你需要给你的按钮添加一个动作监听器,这样你就可以捕捉到点击事件

    ok.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String length = lengthField.getText();
            System.out.println("length=" + length);
        }
    });
    

    为了访问局部变量lengthField,你需要make if final:

    final JTextField lengthField = new JTextField();
    

    这是因为动作监听器是一个匿名的内部类。 JLS 状态

    任何使用但未在内部类中声明的局部变量、形参或异常参数都必须声明为 final。

    另一种选择是将其设为类的实例变量。

    【讨论】:

    • 所以,如果我将所有输入设为最终输入,我可以在 actionlistener 中使用它们吗?因为我认为这会解决我的问题!
    • @benharris 是的,如果声明为 final,您可以访问它们。
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2015-07-01
    • 1970-01-01
    • 2022-06-29
    相关资源
    最近更新 更多