import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class KeyJPanel extends JPanel implements ActionListener{
JButton[] keyButton=new JButton[12];
String[] num={"1","2","3","4","5","6","7","8","9","0",".","BackSpace"};
AbstractPanel selectedPanel;
JTextField inputTextField;
//构造方法,初始化数字键盘页面,输入参数是某个图形面板对象
public KeyJPanel(AbstractPanel selectedPanel){
this.selectedPanel=selectedPanel;
//设置面板的边距
Border lb=BorderFactory.createLineBorder(Color.gray,2);
setBorder(lb);
//设置布局是GridLayout型
setLayout(new GridLayout(4,3));
//创建按钮对象数组,给每个元素注册ActionEvent时间监听器
for(int i=0;i<12;i++){
keyButton[i]=new JButton(num[i]);
keyButton[i].setFont(new Font("Arial",Font.BOLD,15));
keyButton[i].setForeground(Color.BLACK);
keyButton[i].addActionListener(this);
add(keyButton[i]);
}
}
//接口ActionListener中的方法,当单机按钮时,执行此方法
public void actionPerfomed(ActionEvent e){
//获取事件源(某个按钮)
JButton button=(JButton)e.getSource();
//获取KeyJPanel对象所在图形面板上的获得焦点的文本框对象
inputTextField=selectedPanel.getInputTextField();
//inputTextNumber方法负责button对象对inputTextField 的输入
inputNumber(inputTextField,button);
}
//实现数字软键盘对文本框的一次录入工作
public void inputNumber(JTextField tf,JButton button){
//获取上一次单机按钮时文本框内的值,作为旧串
String oldString=tf.getText();
if(oldString==null){
tf.setText(" ");
}
String subStr=oldString.substring(0,oldString.length()-1);
//获取当前按钮的文本信息,作为新串
String newString=button.getText();
//若单机了“BackSpace"键,取字串
if(newString.equals("BackSpace")){
tf.setText(subStr);
}
//若单机了”.“按钮,欧字符串链接
else if(newString.equals(".")){
tf.setText(oldString+".");
}
//若单击了0~9中的任意一个按钮,做字符串的链接
else{
tf.setText(oldString+newString);
}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}