日期:2014-05-20  浏览次数:20634 次

关于文本框输入的疑问。。。求大虾!!
/*
需求:创建一个窗体,在其中加入按钮控件,并添加鼠标事件监听
思路:1 创建窗体,设置窗体参数
2 添加窗体事件监听
3 创建按钮,并加入按钮事件监听
加入鼠标事件监听,
将按钮添加入窗体中
将窗体设为可见;
步骤:
*/
package mousekeytest;
import java.awt.*;
import java.awt.event.*;
class MouseKeyTest
{
public static void main(String []args)
{
new MouseKey();
}
}
class MouseKey
{
private Frame frame;
private Button button;
private TextField tf;
MouseKey()
{
init();
}
public void init()
{
frame=new Frame("my frame");
frame.setSize(200,400);
frame.setLocation(100,100);
frame.setLayout(new FlowLayout());
frameEvent();
button=new Button("my button");
buttonEvent();
mouseEvent();
keyEvent();
frame.add(button);
tf=new TextField(10);
textEvent();
frame.add(tf);
frame.setVisible(true);
}
private void frameEvent()
{
frame.addWindowListener(new WindowAdapter()
{
public void windowOpened(WindowEvent we)
{
sop("窗体打开。。。");
}
public void windowActivated(WindowEvent we)
{
sop("窗体前置,激活中。。。");
}
public void windowClosing(WindowEvent we)
{
sop("窗体关闭。。。");
System.exit(0);
}
});
}
private void buttonEvent()
{
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
sop("按钮动了一下。。。");
//System.exit(0);
}
});
}
private void mouseEvent()
{
button.addMouseListener(new MouseAdapter()
{

int doubleClick=0;
public void mouseEntered(MouseEvent me)
{
System.out.println("鼠标进入组件。。。");
}
public void mouseClicked(MouseEvent me)
{
int count=me.getClickCount();
if(2==count)
System.out.println("鼠标双击组件。。。"+doubleClick++);//想想双击怎么表示?
}
});
}
private void keyEvent()
{
button.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
System.out.println(ke.getKeyChar()+"..."+ke.getKeyText(ke.getKeyCode())+"..."+ke.getKeyCode());
}
});
}
private void textEvent()
{
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
int code=ke.getKeyCode();
if(!(code<=KeyEvent.VK_9&&code>=KeyEvent.VK_0))
{
System.out.println("非法字符"+code);
//ke.consume();
}
}//文本框的定义在这里

});
}
public static <T> void sop(T t)
{
System.out.println(t);
}
}
问题:不过在文本框中输入什么都出现是非法字符提示?求大神解释啊

------解决方案--------------------
你应该是小键盘的数字不行吧!数字小键盘的数字的keycode不在你写的那个范围内的所以不能判断。如果是判断数字可以的话可以用getKeyChar()这个方法得到输入的值! 参考修改如下:
char code = ke.getKeyChar();
if (code>'9'||code<'0') {
System.out.println("非法字符" + code);
}

求给分!!!
呵呵!!!
------解决方案--------------------
探讨

你应该是小键盘的数字不行吧!数字小键盘的数字的keycode不在你写的那个范围内的所以不能判断。如果是判断数字可以的话可以用getKeyChar()这个方法得到输入的值! 参考修改如下:
char code = ke.getKeyChar();
if (code>'9'||code<'0') {
System.out.println("非法字符" + code);
}……