Question

What I am trying to do is keep the user from inputting an empty string into my input. Right now, the user is restricted to typing only numbers. However, nothing keeps them from leaving the text field blank. I want to restrict them from hitting my button to start the program when it is blank.

Right now, my text field is initially left blank and the button is grayed out initially. But when I type something in, the button stays greyed. Keep in mind all this code is in the constructor.

private JTextField plays = new JTextField(7);
DocumentFilter filter = new NumberFilter();
((AbstractDocument)plays.getDocument()).setDocumentFilter(filter);
plays.setToolTipText("Please input an integer.");

if(plays.getText().equals(""))
         play.setEnabled(false);

private class NumberFilter extends DocumentFilter
    {
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) 
        throws BadLocationException
        {
            fb.insertString(offset, text.replaceAll("[^0-9]", ""), attrs);
        }
    }
Was it helpful?

Solution

Right now your filter code just edits to make sure only integer digits are entered into the document.

After the insert you will also need to add an additional check to see if any data has been entered and then enable/disable the text field as required.

Here is an example that uses a DocumentListener to do this:

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;

public class DataEntered implements DocumentListener
{
    private JButton button;
    private List<JTextField> textFields = new ArrayList<JTextField>();

    public DataEntered(JButton button)
    {
        this.button = button;
    }

    public void addTextField(JTextField textField)
    {
        textFields.add( textField );
        textField.getDocument().addDocumentListener( this );
    }

    public boolean isDataEntered()
    {
        for (JTextField textField : textFields)
        {
            if (textField.getText().trim().length() == 0)
                return false;
        }

        return true;
    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void removeUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {}

    private void checkData()
    {
        button.setEnabled( isDataEntered() );
    }

    private static void createAndShowUI()
    {
        JButton submit = new JButton( "Submit" );
        submit.setEnabled( false );

        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        DataEntered de = new DataEntered( submit );
        de.addTextField( textField1 );
        de.addTextField( textField2 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.WEST);
        frame.add(textField2, BorderLayout.EAST);
        frame.add(submit, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

The concept would be the same for a DocumentFilter. You need to do the check when you insert or remove text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top