java按钮以数组形式添加,怎么对每个按钮添加事件?
publicvoidsetPan2(){p2=newJPanel();p2.setLayout(newGridLayout(4,3));String[]name={"1"...
public void setPan2(){
p2=new JPanel();
p2.setLayout(new GridLayout(4,3));
String[] name={"1","2","3","4","5","6","7","8","9","*","0","#"};
for(int i=0;i<name.length;i++){
p2.add(new JButton(name[i]));
}
ActionListener a1=new ActionListener(){
public void actionPerformed(ActionEvent e){
jta.setText(((JButton)e.getSource()).getText());
}
};
//JButton(name[i]).addActionListener(a1);这一行是错误的,也是我不会的,怎么添加,难道还得将每个按钮一一写上再添加?
}
当把一堆的按钮以数组的形式添加进面板以后,后自己又整了个事件监听,怎么把监听添加进数组的每个按钮? 展开
p2=new JPanel();
p2.setLayout(new GridLayout(4,3));
String[] name={"1","2","3","4","5","6","7","8","9","*","0","#"};
for(int i=0;i<name.length;i++){
p2.add(new JButton(name[i]));
}
ActionListener a1=new ActionListener(){
public void actionPerformed(ActionEvent e){
jta.setText(((JButton)e.getSource()).getText());
}
};
//JButton(name[i]).addActionListener(a1);这一行是错误的,也是我不会的,怎么添加,难道还得将每个按钮一一写上再添加?
}
当把一堆的按钮以数组的形式添加进面板以后,后自己又整了个事件监听,怎么把监听添加进数组的每个按钮? 展开
2个回答
展开全部
public void setPan2(){
p2=new JPanel();
p2.setLayout(new GridLayout(4,3));
JButton b;
String[] name={"1","2","3","4","5","6","7","8","9","*","0","#"};
for(int i=0;i<name.length;i++){
//这里,不要直接new JButton,而是新建一个JButton对象,把所有要实现的属性都设置完了,才添加进JPanel的对象里。
//p2.add(new JButton(name[i]));
b = new JButton(name[i]);
b.addActionListener(this);
p2.add(b);
}
ActionListener a1=new ActionListener(){
public void actionPerformed(ActionEvent e){
jta.setText(((JButton)e.getSource()).getText());
}
};
}
注意上述代码中的注释。
p2=new JPanel();
p2.setLayout(new GridLayout(4,3));
JButton b;
String[] name={"1","2","3","4","5","6","7","8","9","*","0","#"};
for(int i=0;i<name.length;i++){
//这里,不要直接new JButton,而是新建一个JButton对象,把所有要实现的属性都设置完了,才添加进JPanel的对象里。
//p2.add(new JButton(name[i]));
b = new JButton(name[i]);
b.addActionListener(this);
p2.add(b);
}
ActionListener a1=new ActionListener(){
public void actionPerformed(ActionEvent e){
jta.setText(((JButton)e.getSource()).getText());
}
};
}
注意上述代码中的注释。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询