您好我正在尝试使用setDocument方法来限制用户可以在文本字段中输入的字符数。但不知何故,它并没有限制输入字符的数量。这是代码
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class JTextFieldCharLimit extends PlainDocument {
private int limit;
public JTextFieldCharLimit(int limit)
{
super();
this.limit = limit;
}
public void inserString(int offset, String str, AttributeSet set) throws BadLocationException
{
if(str == null)
{
return;
} else if((getLength() + str.length()) <= limit)
{
str = str.toUpperCase();
super.insertString(offset, str, set);
}
}
}
我在另一个类中使用此类,我在其中声明了我的文本字段,如下所示:
void playerInfoScreen(JFrame mainFrame, JPanel menuPanel)
{
final ScreenConstructor playerName = new ScreenConstructor();
final JFrame frame = mainFrame;
final JPanel returnPanel = menuPanel;
final JPanel panel = playerName.createPanel("menu panel");
final JButton returnButton = playerName.createButton("MAIN MENU");
final JTextField textEntry = playerName.createTextField(10);
// text field length needs to be set to prevent long texts
final JLabel label = playerName.createLabel("Enter Player Name:");
playerName.addButtonToPanel(panel, returnButton);
playerName.addLabelToPanel(panel, label);
playerName.addJTextFieldToPanel(panel, textEntry);
textEntry.setDocument(new JTextFieldCharLimit(5));
playerName.displayScreen(frame, panel);
// check for esc button to let user return back to main menu
textEntry.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String player = textEntry.getText(); // save entered player name
storedPlayerName = player; // store player in order to use it in highscores and display on game screen
GameScreen game = new GameScreen(frame, panel); // go to game screen
}
});
returnButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setContentPane(returnPanel); // go back to previous panel
}
});
}
答案 0 :(得分:2)
使用DocumentFilter
。有关详细信息,请参阅Implementing a Document Filter和DocumentFilter Examples。
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();
}
}
归功于MDP
((AbstractDocument)textEntry.getDocument()).setDocumentFilter(new SizeFilter(5));