问题内部类。表达错误的非法启动
-
19-09-2019 - |
题
我使用内部类练,但我具有与家庭作业困难的问题:这是如下:
创建扩展JPanel并具有标为“一”,“二”三个JButton的实例Swing组件类BetterButtons,和“三”。在BetterButtons的构造函数,写一个局部类ButtonListener实现的ActionListener。这种局部类有一个字段字符串名称和需要,它分配给该字段名称的String参数的构造函数。该方法无效的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);
}
}
另外,我怎样才能引用该适当值被分配给该字符串变量名?
感谢您预先
解决方案
我觉得你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的每个实例,e.g:
one.addActionListener(new ButtonListener("one"));
不隶属于 StackOverflow