有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java奇怪的Swing编译器时间可访问性错误

这是密码-

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public final class SetLabelForDemo {
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();             
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabeledButton("foo:")); // new JLabeledButton("foo:") is the problem
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private final class JLabeledButton extends JButton{
        public JLabeledButton(final String s){
            super();
            JLabel label = new JLabel(s);
            label.setLabelFor(this);
        }
    }
}

下面是错误消息-

No enclosing instance of type SetLabelForDemo is accessible. Must qualify the allocation with an enclosing instance of type SetLabelForDemo (e.g. x.new A() where x is an instance of SetLabelForDemo).

我完全不理解这个错误。对我来说,一切似乎都是完全正确的。我错过什么了吗


共 (4) 个答案

  1. # 1 楼答案

    您必须将类JLabeledButton声明为静态,因为您要在静态上下文中实例化它:

    private static final class JLabeledButton extends JButton {
        ...
    }
    

    因为您的方法createAndShowGUI是静态的,所以编译器不知道您正在为SetLabelForDemo的哪个实例创建封闭类

  2. # 2 楼答案

    JLabeledButton标记为static

  3. # 3 楼答案

    JLabeledButton类应该是静态的。否则,它只能作为封闭的SetLabelForDemo实例的一部分进行实例化。非静态内部类必须始终具有对其封闭实例的隐式引用

  4. # 4 楼答案

    我知道你已经接受了一个答案,但解决这个问题的另一种方法是在外部类的实例上实例化内部类。e、 g

    private static void createAndShowGUI() {
       final JFrame frame = new JFrame();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.getContentPane().add(
             new SetLabelForDemo().new JLabeledButton("foo:"));
       frame.pack();
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
    }
    

    这是一个有趣的语法,但它是有效的。这与Swing无关,而与在静态上下文中使用内部类有关