Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Access JTextField from another class.....

843785Nov 22 2008 — edited Nov 22 2008
ok the question is simple. How do I access textfield from another class. Here is my example code but it doesn't work

import javax.swing.*;
import java.util.*;

class Test {

JTextField textfield = new JTextField(20);

public void GUI(){ // Creates frame with Textfield - nothing else

JFrame frame = new JFrame();
JPanel panel = new JPanel();

frame.add(panel);

panel.add(textfield);
panel.setLayout(null);

textfield.setBounds(20,40,200,20);
textfield.setText("old text");

frame.setSize(300,200);
frame.setVisible(true);
}

public static void main(String[] args)
{
     new Test().GUI(); // Creates gui
     Thread first = new Test2(); // does thread from Test2 class
     first.start();
}
}

class Test2 extends Thread {
	
	public void run(){

	while (true) {
	    try {
		System.out.println("blah!!");
		Thread.currentThread().sleep(1000);
	} catch (Exception e)
		{
			// do nothing	
		}
	new Test().textfield.setText("NEW TEXT PLEASE!!!!!"); 
///// .... text in my TEXTFIELD from TEST class does not change!!  Why?
// I get the text "blah" from the console but why nothing's happening to my textfield
	}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 20 2008
Added on Nov 22 2008
20 comments
8,513 views