0

hi my Problem was i cant add Buttons to the Action listener i will made a menu i dont know why i become a error here the code package lvl;

import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Main extends JFrame implements ActionListener{

    private JButton button;
    private JButton eintellungen;
    private JButton credits;
    private JButton schliessen;


    public static void main(String[] args) {

        JFrame meinJFrame = new JFrame();
        meinJFrame.setTitle("menu");
        JPanel panel = new JPanel();


    JButton button = new JButton("play");
    JButton schliessen = new JButton("schließen");
    JButton eintellungen = new JButton("einstellungen");
    JButton credits = new JButton("credits");
    panel.add(button);
    panel.add(schliessen);
    panel.add(credits);
    panel.add(eintellungen);
    credits.addActionListener(this);


    meinJFrame.add(panel);


    meinJFrame.setSize(500, 500);

    meinJFrame.setVisible(true);


}

@Override
public void actionPerformed(ActionEvent e) {
                        }


}

} oh i become a error the error says Cannot use this in a static context and it was by credits.addActionListener(this); please help me

coolian
  • 33
  • 8

2 Answers2

1

You are in a static context of public static main. There is no this in static context. Use anonomous class insteed.

    credits.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
        ////    handle action here
    }
});
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

obviously,your class Main and it's method Main(String[] args) is static,and although your Main implements ActionListener,it cant use cause the method addActionListener need a Object ,static method Main has not 'this' context. you can

credits.addActionListener(new YourActionListener());


        meinJFrame.add(panel);


        meinJFrame.setSize(500, 500);

        meinJFrame.setVisible(true);


    }

}
class YourActionListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}

or

credits.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });
C.Sung
  • 3
  • 3