内在阶级的问题。非法开始表达错误

时间:2010-02-10 05:16:23

标签: java swing class inner-classes illegalargumentexception

我正在练习使用内部课程,但我对作业问题有困难:如下:

创建一个扩展JPanel的Swing组件类BetterButtons,它有三个标记为“One”,“Two”和“Three”的Jbutton实例。在BetterButtons的构造函数中,编写一个实现ActionListener的本地类ButtonListener。此本地类具有字段String名称和构造函数,该构造函数接受它分配给字段名称的String参数。方法void actionPerformed在控制台通知上输出已按下标有名称的按钮的按钮。在BetterButtons的构造函数中,创建三个ButtonListener实例,每个按钮用于监听其操作。

我差不多完成了,然而,我在行中得到了非法的表达式错误:

 public void actionPerformed(ActionEvent e){

这是我的代码:

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

public class BetterButtons extends JPanel {
JButton one, two, three;
JPanel p;
public BetterButtons() {
    class ButtonListener implements ActionListener {
        String name;
        *****public ButtonListener(String name) {****
                public void actionPerformed(ActionEvent e){
                    System.out.println("Button "+name+"has been pressed.");
                }
              }
          }
    one = new JButton("One");
    two = new JButton("Two");
    three = new JButton("Three");
    one.addActionListener(new ButtonListener());
    two.addActionListener(new ButtonListener());
    three.addActionListener(new ButtonListener());
    p = new JPanel();
    p.add(one);
    p.add(two);
    p.add(three);
    this.add(p);
}
  public static void main(String[] args) {
    JFrame f = new JFrame("Lab 2 Exercise 2");
    BetterButtons w = new BetterButtons();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(w);
    f.pack();
    f.setVisible(true);
}
}

另外,如何引用要分配给字符串变量名的正确值?

提前谢谢

1 个答案:

答案 0 :(得分:1)

我认为你对buttonListener的定义应该是:

class ButtonListener implements ActionListener {
    String name;
    public ButtonListener(String name) {
            this.name = name;
     }
     public void actionPerformed(ActionEvent e){
                System.out.println("Button "+name+"has been pressed.");
     }

  }

然后将名称传递给buttonlistener的每个实例,例如:

  one.addActionListener(new ButtonListener("one"));