主题:关于获得键盘消息 困惑·
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class JListener extends JFrame implements KeyListener{
Result result=new Result();
Number_key number_key=new Number_key();
//JButton myButton=new JButton();
public JListener(){
super("Text");
setSize(200,200);
setLocation(100,100);
//getContentPane().add(myButton);
getContentPane().setLayout(new BorderLayout());
//getContentPane().add(number_key,BorderLayout.SOUTH);
getContentPane().add(result,BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
}
public void keyPressed(KeyEvent key){
//String str=KeyEvent.getKeyText(code);
//char str=key.getKeyChar();
result.text.setText(Character.toString(key.getKeyChar()));
System.out.println(key.getKeyChar());
}
public void keyTyped(KeyEvent key){
}
public void keyReleased(KeyEvent key){
}
public static void main(String args[]){
JListener myListener=new JListener();
}
}
class Result extends JPanel {
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
public Result() {
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false);
setLayout(new BorderLayout());
add(text, BorderLayout.CENTER);
}
}
class Number_key extends JPanel {
JButton zero = new JButton("0");
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three=new JButton("3");
JButton four=new JButton("4");
JButton five=new JButton("5");
JButton six=new JButton("6");
JButton seven=new JButton("7");
JButton eight=new JButton("8");
JButton nine=new JButton("9");
JButton plus=new JButton("+");
JButton sub=new JButton("-");
JButton mul=new JButton("*");
JButton div=new JButton("/");
JButton equal=new JButton("=");
JButton ce=new JButton("ce");
JButton point=new JButton(".");
JButton d_zero=new JButton("00");
//Font font=new Font("宋体",Font.PLAIN,24);
public Number_key(){
this.setLayout(new GridLayout(6,3,10,10));
add(seven);
add(eight);
add(nine);
add(four);
add(five);
add(six);
add(one);
add(two);
add(three);
add(zero);
add(d_zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
//two.setFont(font);
}
}
为什么不注释//getContentPane().add(number_key,BorderLayout.SOUTH);这行就不能监听键盘消息的?
很是困惑,请高手指点一二。