在 Java Swing 中从 Getter 和 Setter 检索值时遇到问题

问题描述 投票:0回答:2

我在从 Java Swing 中的 getter 和 setter 检索值时遇到问题。我有两个类,

Form1
Form2
,以及用于管理汽车数据的
Car
类。当我在
Form1
中设置一个值并尝试在
Form2
中检索它以将其显示在标签上时,就会出现问题。

这是我的代码的简化版本:

// 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...
}

当我运行此命令时,

Form2
中的标签不显示
bmw
的更新值。此外,我注意到控制台打印了两次该值,这是意外的。

我怀疑我忽略了一些基本的东西,可能与对象实例化或变量范围有关。有人可以帮助我了解出了什么问题以及如何纠正吗?

java swing class oop getter-setter
2个回答
1
投票

您正在 Form2 中创建一个新的 Car 实例,该实例是空的,并且您正在这个空实例上使用 getter。 要从 Form1 检索实例上的数据,您必须将其传递给 Form2,例如通过构造函数:

    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);
    }
}

1
投票

Form2
中,您正在创建一个新的
Cars
实例:

    Cars car = new Cars();

这是与

Form1.actionPerformed
中创建的实例完全不同的实例,因此它将具有完全不相关的值。由于您在此处使用无参数构造函数,因此所有字段都将采用默认值
null

很难说出你的意图是什么,因为这是一个毫无意义的玩具示例,但我最好的猜测是你想将创建的

Cars
实例传递到
Form2
的构造函数中。

Form1.actionPerformed()
中,将创建的实例(称为
car
)传递给构造函数:

            new Form2(car);

Form2
中,接收值并将其分配给字段:

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Form2 extends JFrame {

    Cars car;
    
    public Form2(Cars car) {
        this.car = car;
    
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.