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