Enforce max characters on Swing JTextArea with a few curve balls

前端 未结 3 871
南笙
南笙 2021-01-16 04:48

I\'m trying to add functionality to a Swing JLabel and JTextArea such that:

  • The user is only allowed to enter 500 characters into the textarea (max)
  • T
3条回答
  •  死守一世寂寞
    2021-01-16 05:38

    You can limit the max size by using a DocumentFilter, check this documentation section, it has a working example of what you need.

    Take this as an example, I used the component from the example file above:

    import java.awt.BorderLayout;
    
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    
    import components.DocumentSizeFilter;
    
    public class Test {
    
        public static void main(String[] args) {
            new TestFrame().setVisible(true);
        }
    
        private static class TestFrame extends JFrame{
            private JTextField textField;
            private DefaultStyledDocument doc;
            private JLabel remaningLabel = new JLabel();
    
            public TestFrame() {
                setLayout(new BorderLayout());
    
                textField = new JTextField();
                doc = new DefaultStyledDocument();
                doc.setDocumentFilter(new DocumentSizeFilter(500));
                doc.addDocumentListener(new DocumentListener(){
                    @Override
                    public void changedUpdate(DocumentEvent e) { updateCount();}
                    @Override
                    public void insertUpdate(DocumentEvent e) { updateCount();}
                    @Override
                    public void removeUpdate(DocumentEvent e) { updateCount();}
                });
                textField.setDocument(doc);
    
                updateCount();
    
                add(textField, BorderLayout.CENTER);
                add(remaningLabel, BorderLayout.SOUTH);
    
                setLocationRelativeTo(null);
                pack();
            }
    
            private void updateCount()
            {
                remaningLabel.setText((500 -doc.getLength()) + " characters remaining");
            }
        }
    }
    

提交回复
热议问题