CreateOneButton[] num =new CreateOneButton[48]; CreateFrame(){ JPanel p=new JPanel(); for(int i=0; i<num.length; i++){ num[i]=new CreateOneButton("button"+ i); p.add(num[i]); } getContentPane().add(p); } } 我是随手写的,可能有bug; 从你的源程序看问题可能出在: class CreateFrame extends JFrame {.... CreatOneButton[] num = CreateOneButton[48]; num.addActionListener(this); //this=(CreateFrame)Object, it do not implement the interface ActionListener,so Exception is to be throwed...}
但在JFrame的继承类CreateFrame中我没有加ActionListener,因为我觉得
如果在CreateFrame中加入ActionListener是针对Frame的事件监听,而我希望的是CreateOneButton中的actionPerformed里的
Object source = evt.getsource() 语句,能够返回num[i]对象
你有public actionPerformed(ActionEvent e){}这个事件处理函数吗?
{
...
public void actionPerformed(ActionEvent e)
{
...
}
...
}
class CreatOneButton extends JButton
implements ActionListener
{....
addActionListener(this);
....
public void actionPerformed(ActionEvent e)
{ Object source = e.getSource();
System.out.println(source);
}
}class CreateFrame extends JFrame
{....
CreatOneButton[] num = CreateOneButton[48];
num.addActionListener(this);
}希望的是System.out.println(source)能够返回num[i],也就是说能够指出我按的是那个按钮。这种结构由问题,望大侠们给出好的建议
class CreateOneButton extends JButton implements ActionListener{
CreateOneButton(String name){
super(name);
addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{ Object source = e.getSource();
System.out.println(((CreateOneButton)source).getText());//print "button"+ i
}
}class CreateFrame extends JFrame
{
CreateOneButton[] num =new CreateOneButton[48];
CreateFrame(){
JPanel p=new JPanel();
for(int i=0; i<num.length; i++){
num[i]=new CreateOneButton("button"+ i);
p.add(num[i]);
}
getContentPane().add(p);
}
}
我是随手写的,可能有bug;
从你的源程序看问题可能出在:
class CreateFrame extends JFrame
{....
CreatOneButton[] num = CreateOneButton[48];
num.addActionListener(this); //this=(CreateFrame)Object, it do not implement the interface ActionListener,so Exception is to be throwed...}
您对super()使用的理解,你想得到多少分呢?