如何从 Java 中的内部 class 读取变量?

How can I read a variable from an inner class in Java?

我设计了这个方法来显示 window 和一个滑块,我需要 return 的值。你能告诉我如何检索 JSlider 值吗?目前我收到错误:"local variables referenced from an inner class must be final or effectively final"?

private static int displayFontPanel(JFrame w){
    JFrame window = new JFrame("Font Settings");
    window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    int fontSize = 14;
    window.setSize(400, 200);
    window.setLocationRelativeTo(w);
    JSlider fntSize = new JSlider(8,40,20);
    fntSize.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            fontSize = ((JSlider)evt.getSource()).getValue();
        }
    });
    fntSize.setLabelTable( fntSize.createStandardLabels(8) );
    fntSize.setPaintLabels(true);
    panel.add(fntSize, BorderLayout.CENTER);
    window.setContentPane(panel);
    window.setVisible(true);
    return fontSize;
} 

将方法签名更改为

public void stateChanged(final ChangeEvent evt) {

之后你就可以

((JSlider) evt.getSource()).getValue()

这个答案比我能更好地解释为什么变量需要是最终的:

代码错误是否真的指滑块,而不是 fontSize?如果是后者的话,那你得"cheat"系统一点。闭包中引用的变量必须是最终的,即 - 在以下代码中未更改。

但如果你稍微作弊,将 fontSize 声明为数组 (final int[] fontSize = new int[1]) 并修改其内容,一切都应该有效,如下所示:

fntSize.addChangeListener(new ChangeListener()   {
    public void stateChanged(ChangeEvent evt) {
        fontSize[0] = ((JSlider)evt.getSource()).getValue();
       }
    });

我会使用 AtomicInteger 而不是 int:

    private static int displayFontPanel(JFrame w){
      JFrame window = new JFrame("Font Settings");
      window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      final AtomicInteger fontSize = new AtomicInteger(14);
      window.setSize(400, 200);
      window.setLocationRelativeTo(w);
      JSlider fntSize = new JSlider(8,40,20);
      fntSize.addChangeListener(new ChangeListener()   {
        public void stateChanged(ChangeEvent evt) {
            fontSize.set(((JSlider)evt.getSource()).getValue());
        }
      });
      fntSize.setLabelTable( fntSize.createStandardLabels(8) );
      fntSize.setPaintLabels(true);
      panel.add(fntSize, BorderLayout.CENTER);
      window.setContentPane(panel);
      window.setVisible(true);
      return fontSize.get();
}