尝试在匿名 class 中使用最终变量。但它没有传递价值。我无法理解我的错误

Trying to use final variable in anonymous class. But its not passing the value. I'm unable to understand whats my mistake

我正在使用 SWT 包在 java 中创建 GUI。我试图在两个地方打印相同的两个字符串。我已经将它们定义为最终的。仍然在第一种情况下,它的打印正确。但在内部方法中它只是打印空值。不对的地方请指正

protected void createContents() {
final String inputFile = input.getText(); // input is  Textbox 
final String outputFile = output.getText(); // output is Textbox

System.out.println(inputFile);
System.out.println(outputFile);

btnStartConversion.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            //call conversion.
            try {
                System.out.println(inputFile);
                System.out.println(outputFile);
                @SuppressWarnings("unused")
                Convert convert = new Convert(inputFile,outputFile);
            } catch (IOException | JSONException | InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

您没有使用 Java 8 个闭包 (Lambda)。您正在使用匿名 class。您可能需要直接引用 inputoutput 字段。

假设您的外部 class 被命名为 OuterClass(适当更改)

btnStartConversion.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        //call conversion.
        try {
            System.out.println(OuterClass.this.inputFile.getText());
            System.out.println(OuterClass.this.outputFile.getText());
            @SuppressWarnings("unused")
            Convert convert = new Convert(OuterClass.this.inputFile.getText(),
                                          OuterClass.this.outputFile.getText());
        } catch (IOException | JSONException | InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
});

编辑

(摘自我下面的评论)

我认为问题出在这个匿名 class 处理按钮事件并且需要从一些文本框中获取当前值。通过在对象创建时获取值,它们的值当然是空白或 null。因此,通过直接引用监听器中的字段,您可以在每次单击按钮时获取当前值。