Java从嵌套类返回

Java从嵌套类返回,java,class,methods,actionlistener,event-listener,Java,Class,Methods,Actionlistener,Event Listener,我有这个测试代码,我希望该方法在按下按钮时返回一个值。最好的办法是什么 public String test(){ JFrame frame=new JFrame(); frame.setSize(800,600); frame.setLocationRelativeTo(null); frame.setVisible(true); JButton button=new JButton("Click Me!"); frame.add(button

我有这个测试代码,我希望该方法在按下按钮时返回一个值。最好的办法是什么

public String test(){
    JFrame frame=new JFrame();
    frame.setSize(800,600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    JButton button=new JButton("Click Me!");
    frame.add(button);
}
我已经尝试添加一个
ActionListener
,但是我看不到从父方法返回值的方法

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        //A return here would not work
    }
});

局部变量必须是
final
,但没有什么可以阻止它成为
集合,然后可以对其进行修改

请看下面的代码

public String test(){
    // code
    final List<String> list = new ArrayList<>();
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            list.add("toBeReturned");
        }
    });
    frame.add(button);
    return list.get(0);
}
公共字符串测试(){
//代码
最终列表=新的ArrayList();
addActionListener(新建ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
列表。添加(“toBeReturned”);
}
});
框架。添加(按钮);
返回列表。获取(0);
}

局部变量必须是
final
,但没有任何东西可以阻止它成为
集合,然后可以对其进行修改

请看下面的代码

public String test(){
    // code
    final List<String> list = new ArrayList<>();
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            list.add("toBeReturned");
        }
    });
    frame.add(button);
    return list.get(0);
}
公共字符串测试(){
//代码
最终列表=新的ArrayList();
addActionListener(新建ActionListener()){
@凌驾
已执行的公共无效操作(操作事件e){
列表。添加(“toBeReturned”);
}
});
框架。添加(按钮);
返回列表。获取(0);
}

如果对象是全局对象,则可以更新表单中的对象。直接更新对象而不是返回。使用。它就是为这类任务而设计的。如果对象是全局的,您可以更新表单中的对象。直接更新对象而不是返回。使用。它就是为这种任务而设计的。