0
正试图从json文件中获取所有数据并将数据填充到jtable,我已经从json文件和打印输出中获取数据,但是我无法将数据放在jtable上,当我尝试填充循环内的jtable上的数据,我最终将数据放入框架。请帮助我,我的代码如下:用本地JSON文件填充Jtable
我已经导入了所有需要的jar。
public Main(){
super(new GridLayout(1,0));
BufferedReader br = null;
JSONParser parser = new JSONParser();
String inputline;
try {
br = new BufferedReader(new FileReader("/Users/lyod/Documents/sample.json"));
try {
String id = null,
component = null,
title = null,
lat = null,
lng = null,
cost = null,
status = null;
Object[][] data;
while ((inputline = br.readLine()) != null) {
JSONArray a = (JSONArray) parser.parse(inputline);
String[] columns = new String[] {
"Id",
"Title",
"Component",
"LAT",
"LNG",
"Cost"
};
for (Object o : a) {
JSONObject sample = (JSONObject) o;
id = (String) sample.get("id");
component = (String) sample.get("component");
title = (String) sample.get("title");
lat = (String) sample.get("lat");
lng = (String) sample.get("lng");
cost = (String) sample.get("cost");
status = (String) sample.get("status");
Object[][] data = new Object[][] {
{id,title,component,lat,lng,cost, false },
};
}
JTable table = new JTable(data, columns);
add(new JScrollPane(table));
JFrame frame = new JFrame("test v2");
frame.add(table);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
'当我尝试填充循环内的jtable上的数据时,我最终将数据放大到框架 - 完全相同。为什么你会为循环的每次迭代创建一个新的表格和框架?您应该只在循环完成执行后创建一个表格和一个框架。所以基本的逻辑是在循环开始之前创建一个空的DefaultTableModel。然后在循环中使用DefaultTableModel的addRow(...)方法将数据添加到模型中。然后,循环完成后,使用TableModel创建表并将该表添加到框架。 – camickr
我可以访问循环内的数据吗? – LyodMichael
谢谢我明白了! – LyodMichael