【发布时间】:2016-06-07 14:42:00
【问题描述】:
我是 Java 新手,正在尝试创建一个带有两个按钮的简单 Swing 程序,但我收到了 addActionListener 错误。
public class swingEx1
{
JFrame f;
JPanel p;
JLabel l;
JButton b1,b2;
public swingEx1()
{
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void launchFrame()
{
p.add(b1,BorderLayout.SOUTH);
p.add(b2,BorderLayout.EAST);
p.add(l,BorderLayout.NORTH);
p.setSize(200,300);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
swingEx1 swObj1 = new swingEx1();
swObj1.launchFrame();
}
}
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b1 = (Button) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b2 = (Button) e.getSource();
b2.setLabel("It it Copy Button");
}
}
b1.addActionListener(new ClearButton()) 行产生错误:
类型中的方法addActionListener(ActionListener) AbstractButton 不适用于参数(ClearButton)
b2.addActionListener(new CopyButton()) 行产生错误:
类型中的方法addActionListener(ActionListener) AbstractButton 不适用于参数(CopyButton)
【问题讨论】:
-
对我来说编译得很好。 1) 类名应以大写字符开头。 2)您是否拥有所有正确的导入语句。 3) ActionListener 代码应该引用
JButton而不是“按钮”。 -
我没有收到您描述的错误,但是我确实收到了
JButton到Button转换错误。将所有Button引用替换为JButton -
我正在使用这两个导入:
import javax.swing.*和import java.awt.*,并使用 Eclipse 版本:Mars.2 Release (4.5.2)。即使将 Button 更改为 JButton Eclipse 也会产生相同的错误。