import java.awt.EventQueue; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class LimitTextNum extends JFrame{ private JTextField textField; public LimitTextNum() { super(); setTitle("限制可輸入字符個數的文本框"); getContentPane().setLayout(null); setBounds(100, 100, 337, 243); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { public void keyTyped(final KeyEvent e) { if (textField.getText().length() == 8) { // 限制最多隻能在文本框中輸入8個字符 e.consume(); // 銷燬本次輸入的字符 JOptionPane.showMessageDialog(null, "不能超出可輸入的最大字符個數"); } } }); textField.setBounds(31, 41, 160, 22); getContentPane().add(textField); final JLabel label = new JLabel(); label.setText("限制文本框中可輸入字符的個數"); label.setBounds(32, 17, 207, 18); getContentPane().add(label); // } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { try { LimitTextNum frame = new LimitTextNum(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }