Domanda

Here's my problem. I have a JTextField in which a user inputs a String. In the action controller I am checking if the written String corresponds to another String contained in an object. I would like to make the JTextField case insensitive to whitespaces. I will really appreciate your help.

[Edited] Solved it more easily, using replaceAll("\s+", "") on the Strings; Thank you all for promptness. Kinds regards.

È stato utile?

Soluzione

st.replaceAll("\\s+","") 

removes all whitespaces and non visible characters such as tab and newline. You can use this on the string you get from your JTextField. This is a Regex.

Edit: the string.trim() method is not what you want, because it trims the whitespaces from the start and end of the string, rather than getting rid of all of the whitespace.

Edit 2: If you want to compare strings, use string.equals(str2)

For example, if you have a license plate string called st = "AAA 111" and another called st2 = "AAA111' just strip them of whitespace like this st.replaceAll("\\s+","") and st2.replaceAll("\\s+","") and then you can check if they are equals by st.equals(st2).

Altri suggerimenti

Maybe can you use the FormattedTextField (docs)

JFormattedTextField textField = new JFormattedTextField(this.createFormatter("UUU-###")); // 3 any character uppercase and 3 any valid number

public MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {
        formatter = new MaskFormatter(s);
    } catch (java.text.ParseException exc) {
        System.err.println("formatter is bad: " + exc.getMessage());
        System.exit(-1);
    }
 return formatter;
 }

if you want your JTextField to ignore white-spaces that are being typed by the user in real-time, you can try the code below. This solution overrides the action of keyTyped event of your JTextField.

import javax.swing.JFrame;
import javax.swing.JTextField;

import java.awt.event.*;

public class CustomListenerTextField {

    public static void main(String args[]){
        JFrame frame = new JFrame("Frame Canvas");
        frame.setSize(500, 500);


        JTextField field = new JTextField();
        field.addKeyListener(new KeyListener(){
            @Override
            public void keyTyped(KeyEvent e) {
                // TODO Auto-generated method stub
                if (Character.isWhitespace(e.getKeyChar()) || Character.isSpaceChar(e.getKeyChar())){
                    e.consume();
                }
            }
            @Override
            public void keyPressed(KeyEvent e){

            }
            @Override
            public void keyReleased(KeyEvent e) {
                // TODO Auto-generated method stub

            }
        });
        frame.add(field);
        frame.setVisible(true); 
    }
}   
private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt) { 
//This is the action event of the button.
                                       
    if (GuessTextField.getText().replaceAll("\\s+","").equalsIgnoreCase("what"))
//Ignores the case of the specified TextField.
    {
        JOptionPane.showMessageDialog(null, "You're Awesome");
    }
    else
    {
        JOptionPane.showMessageDialog(null, "Guess Again");
    }
}                      
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top