我已经开始了一个小小的项目来学习如何提取Web数据并学习如何使用Java表。第一次使用表格和2D数组,所以我可能会以错误的方式解决这个问题。 我试图从站点提取数据并将其输入到表中,到目前为止我已经能够获取数据。我将数据输入到一个由逗号和新行(csv)分隔的字符串中,称为scheduleCsv
Sun 02-16-14 09:45 PM,1,REAL TIRED,JUST WACK AT IT,2 - 4,
Sun 02-23-14 08:10 PM,1,BALLERS,REAL TIRED,4 - 11,
Sun 03-02-14 09:00 PM,1,REAL TIRED,EL TRI,1 - 7,
Sun 03-09-14 05:50 PM,1,GO GO POWER RANGERS,REAL TIRED,4 - 9,
Sun 03-16-14 06:40 PM,1,REAL TIRED,GAME OF GROANS,
Sun 03-23-14 09:00 PM,1,HUNGOVER HAT TRICKS,REAL TIRED,
Sun 03-30-14 07:25 PM,1,REAL TIRED,PRESTIGE WORLD WIDE,
Sun 04-06-14 04:20 PM,1,REAL TIRED,BALLERS,
是否可以将此数据输入JTable?我尝试了几种不同的方法来搜索,到目前为止都没有成功。我有另一个数组指定列名
String[] columnNames = {"Date","Field", "Home Team","Visitor Team", "Score"};
我的表格设置如此
final JTable scheduleTable = new JTable(data,columnNames);
我相信"数据"应该是2D数组..?
答案 0 :(得分:1)
根据数据的获取方式,这应该不会那么困难:
"\n"
以获取单独的行,
拆分以获取单独的列一个例子:
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class TableContentsTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = {"Date","Field", "Home Team","Visitor Team", "Score"};
String[][] contents = createTableContents();
JTable table = new JTable(contents, columnNames);
f.getContentPane().add(table);
f.setSize(400,400);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static String[][] createTableContents()
{
String input =
"Sun 02-16-14 09:45 PM,1,REAL TIRED,JUST WACK AT IT,2 - 4,"+"\n"+
"Sun 02-23-14 08:10 PM,1,BALLERS,REAL TIRED,4 - 11,"+"\n"+
"Sun 03-02-14 09:00 PM,1,REAL TIRED,EL TRI,1 - 7,"+"\n"+
"Sun 03-09-14 05:50 PM,1,GO GO POWER RANGERS,REAL TIRED,4 - 9,"+"\n"+
"Sun 03-16-14 06:40 PM,1,REAL TIRED,GAME OF GROANS,"+"\n"+
"Sun 03-23-14 09:00 PM,1,HUNGOVER HAT TRICKS,REAL TIRED,"+"\n"+
"Sun 03-30-14 07:25 PM,1,REAL TIRED,PRESTIGE WORLD WIDE,"+"\n"+
"Sun 04-06-14 04:20 PM,1,REAL TIRED,BALLERS,"+"\n";
String[] lines = input.split("\n");
String result[][] = new String[lines.length][];
for (int i=0; i<lines.length; i++)
{
result[i] = Arrays.copyOf(lines[i].split(","), 5);
}
return result;
}
}
答案 1 :(得分:1)
正如Max谷歌所说,有很多很好的教程。例如: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
要读取cvs文件,我建议你加载到List而不是数组。