I'm encountering an issue with retrieving values from getters and setters in Java Swing. I have two classes, Form1
and Form2
, along with a Car
class for managing car data. The problem arises when I set a value in Form1
and try to retrieve it in Form2
to display it on a label.
Here's a simplified version of my code:
// Form1 Class
public class Form1 extends JFrame implements ActionListener {
JButton btn1;
JTextField tf1;
public Form1() {
// Constructor details...
}
public void actionPerformed(ActionEvent e) {
String b = "";
Car car = new Cars();
if (e.getSource() == btn1) {
b = tf1.getText();
car.setBmw(b);
new Form2();
System.out.println(car.getBmw()); // Printed twice in the console.
}
}
}
// Form2 Class
public class Form2 extends JFrame {
Car car = new Cars();
public Form2() {
JLabel label = new JLabel();
label.setText(car.getBmw());
// Constructor details...
}
}
// Car Class
public class Car {
private String bmw;
public Car() {}
public String getBmw() {
return bmw;
}
public void setBmw(String bmw) {
this.bmw = bmw;
}
// Other getters and setters...
}
When I run this, the label in Form2
doesn't display the updated value of bmw
. Additionally, I noticed that the console prints the value twice, which is unexpected.
I suspect I'm overlooking something fundamental, perhaps related to object instantiation or variable scope. Could someone please help me understand what's going wrong and how to correct it?
You are creating a new instance of Car in Form2 which is empty, and you are using getters on this empty instance. To retrieve data on instance from Form1, you have to pass it to Form2, through constructor for example:
public void actionPerformed(ActionEvent e) {
String b = "";
String v = "";
String m = "";
String r = "";
Cars car = new Cars(b, v, m, r);
if(e.getSource()==btn1) {
b = tf1.getText();
car.SetBmw(b);
new Form2(car);
System.out.println(car.GetBmw());
// Side note, for some reason this will be printed twice in the console.
}
}
public class Form2 extends JFrame {
public Form2(Car car) {
JLabel label = new JLabel();
label.setText(car.GetBmw());
label.setBounds(10, 10, 50, 50);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(250, 180);
this.setLayout(null);
this.setResizable(true);
this.setVisible(true);
this.add(label);
}
}