Actionlistenerns and maybe classes idk (First attempt to Code)

Need Some help :

package FuckingGame;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public  class test1  {

static JFrame Miauz;
 static JLabel abc;
 static JPanel hs;
 static JButton test;
 static int a =0;


 public static void test2() {
Miauz= new JFrame();
Miauz.setTitle("Bestes");
Miauz.setSize(300,300);
 hs= new JPanel();
 test=new JButton("Press me");
 Druck druck= new Druck();
test.addActionListener(druck); 
 abc= new JLabel("Sie haben "+ a + " Geld");

 hs.add(test);
 hs.add(abc);
 Miauz.add(hs);
Miauz.setVisible(true); }   


public static void main (String args[]){
test2();}


public class Druck implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        if( e.getSource() == test){
            a+=1;}
}
}
}

There is an error in the line : Druck druck= new Druck(); but idk why ;-; "No enclosing instance of type test1 is accessible. Must qualify the allocation with an enclosing instance of type test1 (e.g. x.new A() where x is an instance of test1)." This is the errormessage.

1 answer

  • answered 2017-11-12 20:34 Jerome Reinländer

    So the problem here is that Druck is nested in test1. You first need to have an instance of the outer class, before you create an instance of the nested class. Consider this example:

    public class Test {
    
        public Test(){
            System.out.println("Outer Class created");
        }
    
        public class TestInner {
            public TestInner(){
                System.out.println("Inner Created");
            }
        }
        public static void main(String[] args) {
            TestInner inner = new TestInner(); // This is an error
            Test test = new Test(); // Initialization of the containing class
            TestInner inner2 = new TestInner(); // This is no error
            System.out.println("Done");
        }
    
    }
    

    Also take this answer into account.