FrameDemo5
package cn.itcast;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
*
*/
public class FrameDemo5 {
public static void main(String[] args) {
// 创建窗体对象并设置属性
Frame f = new Frame();
f.setBounds(400, 200, 400, 300);
f.setLayout(new FlowLayout());
*
*/
public class FrameDemo5 {
public static void main(String[] args) {
// 创建窗体对象并设置属性
Frame f = new Frame();
f.setBounds(400, 200, 400, 300);
f.setLayout(new FlowLayout());
// 设置窗体关闭
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
super.windowClosing(e);
System.exit(0);
}
});
// 创建Label标签对象
Label la = new Label();
la.setText("请输入数字:");
TextField tf = new TextField(40);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
super.windowClosing(e);
System.exit(0);
}
});
// 创建Label标签对象
Label la = new Label();
la.setText("请输入数字:");
TextField tf = new TextField(40);
// 添加到窗体上
f.add(la);
f.add(tf);
f.add(la);
f.add(tf);
// 给文本框添加键盘事件
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// 判断只能输入数字 先获取字符 ,判断字符,取消事件
char ch = e.getKeyChar();
if (!(ch >= '0' && ch <= '9')) {
e.consume();// 取消事件
}
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// 判断只能输入数字 先获取字符 ,判断字符,取消事件
char ch = e.getKeyChar();
if (!(ch >= '0' && ch <= '9')) {
e.consume();// 取消事件
}
}
});
// 设置窗体可见
f.setVisible(true);
}
}
});
// 设置窗体可见
f.setVisible(true);
}
}