java文本框字数限制,限制键入JTextField的字符数

I figured this would be a simple search on the web but I can't figure this out. Here is what I'm working with so far. Ignore the eventHandler, I know its empty. I want to limit the charField JTextField so that the user can only type one character. I figured this would be easy because of all the apps that limit the amount of numbers you can type when entering State or Zipcode.

To be clear, I'm not looking to validate input, I'm looking to limit input. I want it to ignore keystrokes after one character has been entered.

package Week6;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

import java.io.*;

public class Index extends JPanel{

private JLabel searchLabel;

private JTextArea searchField;

private JLabel charLabel;

private JTextField charField;

public Index(){

GridBagLayout gridbag = new GridBagLayout();

GridBagConstraints c = new GridBagConstraints();

c.fill = GridBagConstraints.NORTH;

setBackground(Color.WHITE);

super.setLayout(gridbag);

searchLabel = new JLabel("Enter text to be searched:");

searchField = new JTextArea("", 5, 20);

JScrollPane scroll = new JScrollPane(searchField);

searchField.setLineWrap(true);

searchField.setWrapStyleWord(true);

searchField.setOpaque(true);

charLabel = new JLabel("Exter a character:");

charField = new JTextField("", 5);

c.insets = new Insets(10, 10, 10, 10);

c.gridx = 0;

c.gridy = 0;

add(searchLabel, c);

c.gridx = 1;

c.gridy = 0;

add(scroll, c);

c.gridx = 0;

c.gridy = 1;

add(charLabel, c);

c.gridx = 1;

c.gridy = 1;

add(charField, c);

CharHandler charhandler = new CharHandler();

charField.addActionListener(charhandler);

}

class CharHandler implements ActionListener{

public void actionPerformed(ActionEvent e){

}

}

}

解决方案

You should use a DocumentFilter for this, take a look at Implementing a Document Filter and DocumentFilter Examples

It will allow you to filter out text coming directly before it's applied to the underlying Document, which makes it flexible enough to be used with any Document implementation that extends from AbstractDocument, takes into account the use cases where the user pastes text into the field or calls setText

For example...

import java.awt.EventQueue;

import java.awt.GridBagLayout;

import java.awt.Toolkit;

import javax.print.attribute.AttributeSet;

import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

import javax.swing.text.AbstractDocument;

import javax.swing.text.BadLocationException;

import javax.swing.text.DocumentFilter;

import javax.swing.text.DocumentFilter.FilterBypass;

public class FilterTest {

public static void main(String[] args) {

new FilterTest();

}

public FilterTest() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {

}

JTextField field = new JTextField(10);

((AbstractDocument)field.getDocument()).setDocumentFilter(new SizeFilter(5));

JFrame frame = new JFrame("Testing");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new GridBagLayout());

frame.add(field);

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

});

}

public class SizeFilter extends DocumentFilter {

private int maxCharacters;

public SizeFilter(int maxChars) {

maxCharacters = maxChars;

}

public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)

throws BadLocationException {

if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) {

super.insertString(fb, offs, str, a);

} else {

Toolkit.getDefaultToolkit().beep();

}

}

public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)

throws BadLocationException {

if ((fb.getDocument().getLength() + str.length()

- length) <= maxCharacters) {

super.replace(fb, offs, length, str, a);

} else {

Toolkit.getDefaultToolkit().beep();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值