Frage

I have looked on the internet and can not find any help with understanding action listeners. I am just starting to learn Java and I have yet to find a good tutorial that helps me understand how to use action listeners. Could someone look over my code or point me in the way of a useful tutorial explaining how to use action listeners?

public static void go implements ActionListener(){
    JFrame j = new JFrame();
    j.setDefaultCloseOperation(EXIT_ON_CLOSE);
    j.setSize(640,480);

    final Screen screen = new Screen();
    j.add(BorderLayout.CENTER, screen);

    JButton button = new JButton("Click Me!");
    button.addActionListener(new ActionListener(){

        public void ActionPerformed(Event e){
            screen.repaint();

        }

    });
    j.add(BorderLayout.NORTH, button);

    j.setVisible(true);
}
War es hilfreich?

Lösung

Other way and much better way is to use Anonymous class. You don't need to implement ActionListener

public static void go(){    // no need to implement actionListener
    JFrame j = new JFrame();
    j.setDefaultCloseOperation(EXIT_ON_CLOSE);
    j.setSize(640,480);

    final Screen screen = new Screen();
    j.add(BorderLayout.CENTER, screen);

    JButton button = new JButton("Click Me!");
    button.addActionListener(new ActionListener(){ // change are made here

        @Override
        public void actionPerformed(ActionEvent e) {  //& here
            screen.repaint();
        }
    });
    j.add(BorderLayout.NORTH, button);
    j.setVisible(true);
}

Andere Tipps

actionPerformed is a method of interface, its not a class.

So use actionPerformed insted of ActionPerformed and use annotation @Ovveride for ovveriding the actionPerformed to provide your own defination.

        @Override
        public void actionPerformed(ActionEvent e) {
            screen.repaint();
        }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top