Miguel Remulta
Miguel Remulta

Reputation: 73

Accessing Enclosing Class inside anonymous class

suppose i have a code in java like this

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class GUIExercise {
    private static void createAndShowGUI () {
        JFrame frame = new JFrame("My Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel center = new JPanel();
        center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));

        JLabel label = new JLabel("Migz");
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setFont(label.getFont().deriveFont(Font.ITALIC | Font.BOLD));

        center.add(label);
        JButton btn = new JButton("Click me");
        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed (ActionEvent e) {
                JOptionPane.showMessageDialog(GUIExercise.this, "Font.ITALIC is " + Font.ITALIC + " and Font.BOLD is " + Font.BOLD + " finally Font.ITALIC | Font.BOLD is " + (Font.ITALIC | Font.BOLD), "Ni Hao", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        center.add(btn);

        frame.getContentPane().add(center, BorderLayout.CENTER);
        frame.pack();
        frame.setSize(frame.getWidth() + 100, frame.getHeight() + 50);
        frame.setVisible(true);
    }

    public static void main (String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run () {
                createAndShowGUI();
            }
        });
    }
}

putting GUIExercise.this in the first parameter of showmessagedialog will result in error: non-static variable this cannot be referenced from a static context. what must be done? or how can i access the EnclosingClass?

Upvotes: 0

Views: 96

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280173

It seems like you're trying to use that code in a static method. You cannot access an enclosing instance from a static context, since there is no instance.


That isn't the problem. The issue is that you are trying to execute the method directly in the body of the class. You can't do that. You'll have to put it in a method, probably the method you are meant to override as part of the ActionListener interface.

btn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(EnclosingClass.this, "Hello");
    }
});

(Assuming EnclosingClass is a Component.)

Upvotes: 2

Related Questions