日期:2014-05-20 浏览次数:20795 次
public class Test2 extends JFrame { JPanel pane; JTextField text; JLabel str; public Test2() { super("字符输入限制"); pane = new JPanel(); getContentPane().add(pane); text = new JTextField(12); str = new JLabel("最多可输入 5 个字符:"); text.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { if (text.getText().length() > 4 && e.getKeyChar() != '\b') e.setKeyChar('\0'); } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } }); pane.add(str); pane.add(text); } public static void main(String[] args) { SwingConsole.run(new Test2(), 200, 200); } }