
可以这样改J1.add(new JButton("btn"+i))->J1.add(new JButton(new MyAction(参数)))
MyAction是实现了Action接口的用户自定类,
可以直接用MyAction implements Action来实现,不过这样比较复兄肆杂,必须实现接口中的所有方法。羡搜轿
建议用MyAction extends AbstractAction编写较为简单。
import java.awt.FlowLayoutimport java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JTextField
public class ShowButton implements ActionListener{
private JTextField textField = null
private JButton button = null
private JFrame frame = null
public ShowButton(){
frame = new JFrame("显示按钮文字")
button = new JButton("3")
textField = new JTextField("",20)
frame.setLayout(new FlowLayout(FlowLayout.CENTER))
frame.add(textField)
button.addActionListener(this)
frame.add(button)
frame.setSize(400, 100)
frame.setResizable(false)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setVisible(true)
}
public void actionPerformed(ActionEvent e) {
textField.setText("")
textField.setText(button.getActionCommand())
System.out.println(button.getActionCommand()+"===")
}
public static void main(String[] args) {
new ShowButton()
}
}
你a[i][j].addActionListener(this)这改谈句就是给按简绝钮加监听啊,你想给哪些按钮加就在哪些按钮上调用addActionListener(this)方法。你的类还实现拦歼姿ActionListener接口,并补全actionPerformed方法,添加监听的方法才不会报错。
有问题的话再问,把问题描述的具体些。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)