Java single character textbox help

snotnose

Ars Praefectus
3,453
Subscriptor
A few years ago I wrote a Soduko solver in Java. Works great, except I have to edit the source file to change the input because I could never get Swing to work like my mental model said it should.

Cut to now, I want to figure out Swing. Each cell takes a single character, 1-9 or " ". The space could be 0 and I can deal with that elsewhere if need be. If a valid character is entered move to the next box, otherwise set the cell to " " (or 0) and stay on that cell. Of course, the user can click on any cell to focus on it.

I've got it working (out of frustration) with a JComboBox. But it's ugly. Man is it ugly.

Seems a JTextBox is the way to go but I'm not having much luck wrangling it into what I'm trying to do. Ideally for every character typed it would generate an event. My event handler would validate the input, if good use the value and goto the next cell. If validation fails leave the existing value alone and stay on this cell.

Not really looking for code, more like a roadmap of terms to feed Google. I suspect what I'm really missing is the list of various events I can (should) handle.
 

alcachofas

Wise, Aged Ars Veteran
109
Subscriptor
Been a little while but I think you’re just looking for adding listeners.

Depending on how you want to do it you can respond to key presses - eg to validate the key before allowing it to be entered - in which case you probably want keylisteners or you can do the probably more simple thing of watching the backing data with a documentlistener

Edit: this should probably be enough to get you started https://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield
 
ChatGPT experiment - first answer (it could be insane)

Using Java and the swing framework, provide example code for handling a text field with a single character input. Provide filters for the character inputs to restrict values to 1-9 and " ".​


Certainly! You can use a JTextField in Java Swing to handle single character input with the specified filters. Here's an example code snippet that demonstrates how to create a JTextField with the desired character input restrictions:

Java:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class SingleCharacterInputExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Single Character Input Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextField textField = new JTextField(1); // Create a JTextField with a maximum length of 1
        PlainDocument doc = (PlainDocument) textField.getDocument();
        doc.setDocumentFilter(new DocumentFilter() {
            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                    throws BadLocationException {
                String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
                currentText = currentText.substring(0, offset) + text + currentText.substring(offset + length);
                if (isValidInput(currentText)) {
                    super.replace(fb, offset, length, text, attrs);
                }
            }
        });

        textField.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (!isValidInput(String.valueOf(c))) {
                    e.consume(); // Consume the key press if it's not a valid input
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

        frame.add(textField);
        frame.pack();
        frame.setVisible(true);
    }

    private static boolean isValidInput(String text) {
        // Check if the input is a digit between 1 and 9 or a space
        return text.matches("[1-9 ]");
    }
}

In this code:

1. We create a JTextField with a maximum length of 1 to restrict it to single character input.
2. We set a DocumentFilter to filter text changes and ensure they conform to the allowed input pattern of digits 1-9 and space.
3. We add a KeyListener to validate individual key presses, consuming the key press if it's not a valid input character.

This code should create a Swing application with a JTextField that allows only single character input consisting of digits 1-9 and space.
 
Last edited: