- package AWT;
- import java.awt.Button;
- import java.awt.FlowLayout;
- import java.awt.Frame;
- import java.awt.TextArea;
- import java.awt.TextField;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import javax.swing.JOptionPane;
- public class KeyEventDemo {
- /**
- * 键盘事件
- * 将输入文本框中的内容显示在文本区域
- */
- public static void main(String[] args) {
- new KeyEvents("键盘事件");
- }
- }
- class KeyEvents extends Frame {
- //创建成员变量
- private TextField tf = null;
- private TextArea ta = null;
- private Button b = null;
- public KeyEvents(String title) {
- init();
- }
-
- //初始化窗体和组件
- private void init() {
- setBounds(200, 300, 500, 600);
- setLayout(new FlowLayout());
- b = new Button("转到");
- tf = new TextField(60);
- ta = new TextArea(25, 75);
- add(tf);
- add(b);
- add(ta);
- setVisible(true);
- //监听事件
- events();
- }
- //创建事件监听
- private void events() {
- //添加窗体监听,关闭窗体
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- //添加文本框的键盘监听
- tf.addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- //回车则将输入内容显示在文本区域
- if (e.getKeyChar() == KeyEvent.VK_ENTER){
- showInfo();
- JOptionPane.showMessageDialog(null, "回车按下了");
- }
- }
- });
- //添加按钮监听,单击鼠标触发事件
- b.addMouseListener(new MouseAdapter() {
- public void mouseClicked(MouseEvent e) {
- showInfo();
- // ta.append(tf.getText());
- JOptionPane.showMessageDialog(null, "鼠标点击了");
- }
- });
- }
- //显示信息
- private void showInfo() {
- tf.setText("");//你把它先清空了...
- String str = tf.getText();
- System.out.println("str= "+tf.getText());
- ta.append(str);
- }
- }
复制代码 写窗体,建议不要用awt, 用swing好一些.你的窗体设计不合理,文本域超过窗体了.如果输入一俩个字符,正常是看不到的. |