Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Swing compile-time accessibility error

Here is the code -

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);
        }
    }
}

And here is the error message -

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).

I don't understand this error at all. To me, everything seems perfectly valid. Am I missing something?

like image 988
mre Avatar asked Mar 19 '26 19:03

mre


2 Answers

You'll have to declare your class JLabeledButton static since you instantiate it within a static context:

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

Because your method createAndShowGUI is static the compiler does not know for which instance of SetLabelForDemo you are creating the enclosed class.

like image 55
Howard Avatar answered Mar 21 '26 07:03

Howard


The JLabeledButton class should be static. Else, it can only be instantiated as part of an enclosing SetLabelForDemo instance. A non static inner class must always have an implicit reference to its enclosing instance.

like image 30
JB Nizet Avatar answered Mar 21 '26 09:03

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!