-2

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.

  • You may want to provide a bit more detail about what you are trying to achieve. Also, what have you tried to do to fix this? – Michael Harper Nov 12 '17 at 20:22
  • I want to increase a when u click on the button. i dont even know what i tried cause this is like my first attempt to try something ._. – klallenmann Nov 12 '17 at 20:24

1 Answers1

0

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.

Jerome Reinländer
  • 1,227
  • 1
  • 10
  • 26