Sayful Adrian Sayful Adrian -4 years ago 75
Java Question

I wanna make a simple code from this

So, I have for JTextfields in my program, but if I check it whether empty or not, it will make my code longer and not effective. Is there any code that simpler than this?

if (t_ipA.getText() == null || t_ipA.getText().trim().isEmpty()) {
// your code here

Note : I have : t_ipA .. t_ipD, t_maskA .. t_maskD
There is eight JTextfields.

Okay, now I have resolved my own question.

this is the code, I've been using :
This is the method :

private boolean isEmpty(JTextField f) {
if (f==null || f.getText().trim().isEmpty()) {
return f.getText().trim().isEmpty();


and this is in actionlistener :



But then, I still searching for using array list for make this code simpler.

Thanks to QBrute, JBNizet, and Mureinik

Answer Source

First, you can define a method to encapsulate the check:

private boolean isEmpty(JTextField f) {
    return f.getText() == null || f.getText().trim().isEmpty();

Then, you could place all your fields in a list or array, and use Java 8's streaming API to apply the condition to all of them. E.g.:

List<JTextFeild> fields = Arrays.asList(t_ipA, t_ipB /* etc... */);
if ( {
    // your code here...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download