我要创建一个 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 对象,例如:
WeatherGUI 框架 = new WeatherGUI(FileReader.readWeatherInfos());
(其中 readWeatherInfos()
将具有类似 public static List<Weather> readWeatherInfos()
的签名)。或者略有不同,例如:
List<Weather> tempWeather = new FileReader().readWeatherInfos();
WeatherGUI frame = new WeatherGUI(tempWeather);
(这里假设您的读取方法不是静态的)
您关于不在类(class)中设置任何静态内容的说法是正确的。 weather
你类(class)的领域是完全正确的。但在 WeatherGUI 对象实例化之前,您根本无法访问该字段!
关于java - 将信息从 ArrayList 从一个类传递到 WindowsBuilder GUI 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413788/