将信息从一个类从 ArrayList 传递到 WindowsBuilder GUI 类



我要创建一个GUI,它将我读入的数据放入ArrayList中,并对这些数据执行操作,例如显示,排序和计算。

我的信息是天气数据。

在一个名为"FileReading"的类中,我将我的数据从csv读取到ArrayList中。然后,我需要将此信息传递给名为"WeatherGUI"的JFrame GUI类,并对数据执行上述操作。

我在将信息从我的 ArrayList 传递到我的 GUI 类时遇到问题。由于我已经测试过它可以将数据读取到 ArrayList 中,因此我不会包含该代码。

这是我在 WeatherGUI 类中的相关代码,我将在下面描述错误

public class WeatherGUI extends JFrame implements ActionListener {
private ArrayList<Weather> weather;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherGUI frame = new WeatherGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherGUI(ArrayList<Weather> weather) {
super("Weather");
this.weather = weather;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 692, 561);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}

我遇到的错误是在try语句中,WeatherGUI想要一个与我的ArrayList相关的参数,我不确定在这里放什么。如果我输入"天气",它会告诉我将天气设为静态,我知道这是不正确的。我添加的代码是讲师在幻灯片中提供的代码,但我仍然收到错误。

在这里:

WeatherGUI frame = new WeatherGUI();

您设计的类的方式是 WeatherGUI 在创建时需要一个列表(更喜欢在方法签名中使用列表而不是 ArrayList!)。这是有道理的。

但这意味着:在创建 GUI 对象之前,您必须读取该 List 对象,例如:

WeatherGUIframe = new WeatherGUI(FileReader.readWeatherInfos());

(例如,readWeatherInfos()将具有像public static List<Weather> readWeatherInfos()这样的签名)。或者略有不同,例如:

List<Weather> tempWeather = new FileReader().readWeatherInfos();
WeatherGUI frame = new WeatherGUI(tempWeather);

(这里假设你的读取方法不是静态的)

你关于在你的课堂上做任何静态的东西是正确的。您类的weather字段是完全正确的。但是,WeatherGUI 对象实例化之前,您根本无法访问该字段!

最新更新