Zachary Schmalz
Zachary Schmalz

Reputation: 63

Compare data from JTextArea in Java

I have 4 JTextFields, a JButton, and a JTextArea component in a panel.

The user enters a string in the 4 text fields, and when the button is clicked, the strings in the text field are appended into the text area. The text fields are cleared for the next set of inputs to be displayed

If the user enters data that is exactly the same for 3 of the fields that was previously entered and displayed in the text area, a error message is displayed.

My question is, how can I compare the data in the text fields to the data that has already been displayed in the JTextArea?

It looks like this:

enter image description here

Upvotes: 0

Views: 807

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

You could use String#contains to compare the contents of the JTextArea with the JTextFields, for example...

if (!textArea.getText().contains(textField.getText()) {
    // Not included in text area
}

The problem with this, is it doesn't distinguish between "words", for example an will match banana. Without knowing how you are separating your words, it's difficult to make a suggestion, you might be able to use a regular expression, but we'd need more information before knowing how that might work.

Another solution would be to add each value from the text fields to a List and use it to instead...

if (!listOfValues.contains(textField.getText())) {
    listOfValues.add(textField.getText());
    // Append to text area, do other stuff
} else {
    // Show error message
}

Upvotes: 2

Related Questions