0

I'm trying to pass a JTEXTFIELD value I created in class 2 to class 3. My terminal when compiling shows me this:

error: incompatible types
        username = class2.username;

My code structure is this.

    class 1
    - has main
    -class2 c2 = new class2

    class 2 (extends JFrame)
    - JTextField username = new JTextField("", 15);
    -method gui here
    -method actionlistener here
       if e.getsource == submit
          class3 c3 = new class3
          c3.connection();

class 3
-method connection
-string username declared here
- username = class2.username

How can i get the value from class 2 into class 3?

4
  • 2
    For help with code, quote code. Commented Mar 30, 2014 at 23:30
  • right so what do I do? get the value of the textfield then pass to string? Commented Mar 30, 2014 at 23:32
  • cheers for that. Wasn't aware you could use another . in a statement. Isit possible to give comments "best answer" ? Commented Mar 30, 2014 at 23:34
  • I'll write my comment as an answer and you can accept it Commented Mar 30, 2014 at 23:36

1 Answer 1

1

You were getting the error because you are assigning JTextField to a String which would result in incompatible types error.

To be able to get the value of JTextField you have to use the getText() method like so:

username = class2.username.getText();

getText() returns a String which you can then assign to any String you like.

Here is the documentation for getText(): http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#getText()

Sign up to request clarification or add additional context in comments.

2 Comments

THats actually not working. No data gets passed? Any idea why? I did a system out on class 2 and it showed my data but in class 3 nothing was displayed on system.out
@Bobski It is difficult to tell what's going on without seeing the code but I would assume your problem has to do with initialization order. Check this out: norvig.com/java-iaq.html#init and also docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4 to understand that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.