awhitesong
awhitesong

Reputation: 95

illegal forward reference netbeans swing

I am building a GUI with swing in netbeans. In Designing GUI,netbeans instantiates all the variables at the end of the program which cannot be manipulated.Now I want to get the Jtextfield data and put it in a String object. Suppose netbeans created my JTextField variable as jTextField1 and if I do

String name=jTextField1.getText() at the beginning

it shows the error of illegal forward reference and if I try to define this at the end of the program(after all netbeans' declarations)it throws millions of exceptions.

So what should I do to declare this string object and retrieve the value of gettext() in a variable?

EDITED:

//The code

import javax.swing.JOptionPane;



public class LoginInternalFrame extends javax.swing.JInternalFrame

{



public LoginInternalFrame() 
{
    initComponents();
}


public int check()
{
    if(jTextField1.getText().equals(""))
    {
        return 0;

    }
    if(jPasswordField1.getText().equals(""))
    {
        return 0;

    }

       return 1;     
}

//HERE I AM TRYING TO DECLARE ********************

 String user = jTextField1.getText();

//THIS IS SHOWING ILLEGAL FORWARD REFERENCE BECAUSE jTextField IS DECLARED AT THE END OF THE CODE WHICH IS UNMODIFIABLE IN THE IDE



//HERE STARTS NETBEANS' GENERATED CODE 

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jPasswordField1 = new javax.swing.JPasswordField();
    jButton1 = new javax.swing.JButton();

    setClosable(true);
    setIconifiable(true);
    setMaximizable(true);
    setResizable(true);

    jLabel1.setFont(new java.awt.Font("Tekton Pro", 0, 18)); // NOI18N
    jLabel1.setText("Username");

    jLabel2.setFont(new java.awt.Font("Tekton Pro Ext", 0, 18)); // NOI18N
    jLabel2.setText("Password");

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jButton1.setFont(new java.awt.Font("Tarzan", 1, 18)); // NOI18N
    jButton1.setText("Login");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(213, 213, 213)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(127, 127, 127)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 245, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(351, 351, 351))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(93, 93, 93)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(49, 49, 49)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(84, 84, 84)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(145, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold> 

//NETBEANS' GENERATED CODE ENDS.

//THE ACTIOINPERFORMED METHODS

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if(check()==0)
        {
            JOptionPane.showMessageDialog(this, "All Fields are Required...","Error",JOptionPane.ERROR_MESSAGE);
            return;
        }
    WelcomeUser ww=new WelcomeUser();
     ww.setVisible(true);
     this.setVisible(false);

}                                        

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            

}                                           

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   

//THESE ARE THE UNMODIFIABLE DECLARATIONS IN THE END.NOW WHEN I TRY DECLARE STRING HERE ,THE IDE SHOWS A LOT OF EXCEPTIONS.

}

and I am not able to get the textfield's text in the string variable.

Upvotes: 3

Views: 547

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

My guess is that you have the name String declared in the initialization portion of the code, outside of any constructor or method, and so before your jtf JTextField has been declared. If so, the solution is, yeah, OK, declare name in this region, but don't try to initialize it with the JTextField's text yet.


Edit: yep, I'm right -- you're declaring the user variable outside of any constructor or method, and that is fine, but you're also trying to initialize it there with the JTextField jTextField1's text as well, and that doesn't make sense. Not only isn't the text field variable yet declared, but even if it were declared, it's not even constructed yet. And even if it were constructed, it wouldn't hold any useful text as the user hasn't had a chance to fill it with text yet.

Solution: initialize your String with an empty String, "", and then in some sort of event, perhaps an ActionListener that the user calls after he has filled the text field with text, give your name variable the text held by your JTextField.

Edit 2: Thanks for improving your question!


Edit 3
You state in comment:

But there is still one conceptual problem that say when I press "enter" button on my gui page(without writing anything in the text field),the check function gets invoked(in my program)and there in the if statement getText works?(So there is STILL nothing written in the textfield and the jTextField1 has also not been declared yet!)

Actually yes, it has now been declared, and now may have text within it (if the user presses enter after entering text). It's not so much important where you access the variable geographically in the code, unless you're within the same scope level, but rather where you access it logically. Since you're accessing it from a non-static method, and since your JTextField variable is declared in the declaration part of your class, the compiler knows that it has been declared already.


Edit 4
A key concept is to understand what objects can and cannot do, and that Strings are immutable -- cannot be changed. Note that if your initial declaration were allowed, it would still not be helpful, since when the JTextField's text changed, your name variable would not. The only way for it to change would be for you to assign a new String (likely the new one in the JTextField) when needed, when an event occurs. There's no magic in Java.

Also as an aside regarding your check() method, since it returns a binary result, why not make it return boolean. Also, you should not call getText() on a JPasswordField as that greatly reduces the security of your program as it exposes the password text. I'd do something like:

//!! make this boolean
public boolean check() {
  if (jTextField1.getText().trim().isEmpty()) {
     return false;
  }
  if (jPasswordField1.getPassword().length == 0) {
     return false;
  }
  return true;
}

and then call it like so:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   if (check()) {
      // ....

Upvotes: 3

Related Questions