java - 如何将变量设置为等于用户在 JDialog 中输入的内容?

标签 java swing actionlistener jdialog

所以我试图从 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);


 }

在顶部您可以看到我希望用户输入哪些信息。

按下“确定”按钮后,我想让局部变量等于用户输入的内容,然后将这些变量返回到我的主类进行处理。 我觉得我需要一个“确定”按钮上的 Action 监听器,但是当我这样做时,局部变量无法使用,现在我很困惑。如何使局部变量等于用户输入的内容?

最佳答案

您需要向按钮添加一个 Action 监听器,以便捕获点击事件

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

为了访问局部变量lengthField,您需要将其设置为final:

final JTextField lengthField = new JTextField();

这是因为 Action 监听器是一个匿名内部类。 JLS

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

另一种选择是使其成为类的实例变量。

关于java - 如何将变量设置为等于用户在 JDialog 中输入的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875444/

相关文章:

JavaScript:在 <span> 中包含/附加对象/按钮

java - Spring 启动 : Cannot change version of project facet to 3. 1

java - 拥有匿名实现的 ActionListener? (忙光标)

java - JButton打印一封信

java - 如何检查并防止更改 JTabbedPane 上的选项卡?

java - 如何在另一个类中调用Java类中的变量

Java swing-在鼠标单击事件中使用范围之外的 boolean 值?

java - 解决 Java 内存泄漏的方法

java - 想知道现在在 java 中执行哪个 Jenkins 作业

java - 基于另一个 ComboBox 的项目禁用 JComboBox