事件适配器作为内部类

时间:2016-03-10 18:52:29

标签: java swing

以下是什么问题?我已完全按照书中所示实现了适配器类,但我的编译器不接受他的代码部分:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Eevento{
   public static void main(String[] args){
      JFrame frame = new JFrame("Wumbleton");
      Container content = frame.getContentPane();
      JButton button1 = new JButton("Press this");
      content.add(button1, BorderLayout.NORTH);
      button1.addMouseListener(new MouseAdapter{
                                 public void mousePressed(MouseEvent e){
                                    System.out.println("button 1 has been                pressed");
                                 }
                                });

      frame.setVisible(true);
      frame.setSize(500,500);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

1 个答案:

答案 0 :(得分:4)

在适配器的构造函数方法之后,您缺少括号:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Eevento {
   public static void main(String[] args){
      JFrame frame = new JFrame("Wumbleton");
      Container content = frame.getContentPane();
      JButton button1 = new JButton("Press this");
      content.add(button1, BorderLayout.NORTH);
      button1.addMouseListener(new MouseAdapter(){ // parentheses added
          public void mousePressed(MouseEvent e){
               System.out.println("button 1 has been pressed");
          }
      });
      frame.setSize(500,500);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}