public class MyFrame extends JFrame implements ActionListener{
public MyFrame() {
....
button2.addActionListener(this)
}
/**
* 按钮二的袜猜正事件响应在此
*/
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button2){
showMsg("你按下了" + button2.getText())
}
...
}
}
先定义一个监听器al:ActionListener al = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String str = btn1.getText()
field.setText(str)
}
}
然后所液念粗有button都调用addActionListener(al)这样al就可高简以监闹镇听所有button的点击事件了.通过e.getSource()获取哪个按钮,然后获取按钮上的数字即可.
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()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)