문제

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);
}
도움이 되었습니까?

해결책

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);
}

다른 팁

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();
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top