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