Reputation: 133
I have two classes, both extending JFrame
.
public class A extends JFrame {
JTextField pA, pB;
String a1, b2;
public A()
{
pA = new JTextField (10);
pA.setEditable(false);
pA.setText(""+a1);
pB = new JTextField (10);
pB.setText(""+b2);
pB.setEditable(false);
add(pA); add(pB);
}
}
And in my other class:
public class B extends JFrame implements ActionListener
{
String a, b;
JButton ok;
JTextField jtext1, jtext2; //where the user will input names
public B()
{
jtext1 = new JTextField(10);
jtext2 = new JTextField(10);
ok = new JButton("OK");
ok.addActionListener(this);
add(jtext1);
add(jtext2);
add(ok);
}
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == ok)
{
a = jtext1.getText();
b = jtext2.getText();
if (!a.equals("") && !b.equals("") {
A x = new A();
x.a1 = a;
x.b2 = b;
}
else
{
//some code
}
}
}
}
I'm not getting any errors, but the problem is when I click ok
in class B
, class A
will pop up and is supposed to display the users' names via text fields, but it doesn't.
Upvotes: 1
Views: 92
Reputation: 8826
You try to set them after constructor which you set textfields in the constructor. Send them as parameters to constructor and create text fields.
public A( String a1, String b1){
pA = new JTextField (10);
pA.setEditable(false);
pA.setText(a1);
pB = new JTextField (10);
pB.setText(b2);
pB.setEditable(false);
add(pA); add(pB);
}
Upvotes: 3
Reputation: 285403
You're code is trying to work under the beginner's fallacy, that if you assign an object to two variables, and then change the assignment of one of the variables, the 2nd variable will magically change assignments, and it doesn't work that way.
Your B class changes the values held by A's Strings, but after A has already used the original Strings to set the A text fields.
The solution: give A public setter methods that allow other classes the ability to set the text in its text fields.
i.e.,
public class A extends JFrame {
JTextField pA, pB;
public String a1, b2;
public A() {
pA = new JTextField (10);
pA.setEditable(false);
pA.setText(a1);
pB = new JTextField (10);
pB.setText(b2);
pB.setEditable(false);
setLayout(new FlowLayout);
add(pA);
add(pB);
}
public void setPaText(String text) {
pA.setText(text);
}
public void setPbText(String text) {
pB.setText(text);
}
}
Or give A a constructor that allows outside classes the ability to set the fields on object creation. Or do both!
Upvotes: 3