我是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)
最佳答案
在您的两个内部类中,您应该使用JButton并使用Button。这可能就是为什么您要获得例外。我使用建议的更改运行了您的代码,但没有任何错误。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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) {
JButton b1 = (JButton) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b2 = (JButton) e.getSource();
b2.setLabel("It it Copy Button");
}
}