1.方法1
????????不提供任何數(shù)據(jù)喇嘱,也不創(chuàng)建列和行簸搞。
1.1代碼
public class Main {
public static void main(String[] args){
JFrame jf = new JFrame("JTable");
jf.setBounds(400, 200, 1000, 800);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane=new JScrollPane();
JTable table=new JTable();
GroupLayout groupLayout=new GroupLayout(jf.getContentPane());
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
scrollPane.setViewportView(table);
jf.setVisible(true);
}
}
1.2效果
方法一效果
????????從圖片可以直觀的看出扁位,生成的就是零行零列的表,從界面來看就是一片空白趁俊,啥都沒有域仇,沒啥好說的。
2.方法2
????????不提供任何數(shù)據(jù)寺擂,但是創(chuàng)建列和行暇务。
2.1代碼
public class Main {
public static void main(String[] args){
JFrame jf = new JFrame("JTable");
jf.setBounds(400, 200, 1000, 800);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane=new JScrollPane();
JTable table=new JTable(10,3);
GroupLayout groupLayout=new GroupLayout(jf.getContentPane());
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
scrollPane.setViewportView(table);
jf.setVisible(true);
}
}
2.2效果
方法二效果-1
????????從圖中可以很容易地發(fā)現(xiàn)一個有意思的地方泼掠,那就是表的列頭竟然是ABC,因為我們是沒有提供表頭的般卑,那么如果把當(dāng)前的3列改為27武鲁,會怎么樣呢?
方法二效果-2
????????通過上面兩張圖蝠检,可以很明顯的得出一個結(jié)論沐鼠,就是在我們沒有提供列頭的情況下,Java會默認(rèn)提供列頭叹谁。但是這種情況饲梭,很明顯不是我們想要的顯示結(jié)果。
3.方法3
????????提供數(shù)據(jù)(單元格內(nèi)容和列頭)并且創(chuàng)建列和行焰檩。
3.1代碼
public class Main {
public static void main(String[] args) {
JFrame jf = new JFrame("JTable");
jf.setBounds(400, 200, 1000, 800);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
JTable table = getThreeMethodTable();
GroupLayout groupLayout = new GroupLayout(jf.getContentPane());
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane));
scrollPane.setViewportView(table);
jf.setVisible(true);
}
private static JTable getThreeMethodTable() {
String[][] data = new String[][]{{"1", "1", "1"}, {"2", "2", "2"}, {"3", "3", "3"}};
String[] columnNames = new String[]{"test1", "test2", "test3"};
JTable jTable = new JTable(data, columnNames);
return jTable;
}
}
3.2效果
方法三效果
????????這種方法是一般最常用的方法憔涉,也是最基礎(chǔ)最簡單的方法,但正因為最基礎(chǔ)析苫,所以有很大局限性兜叨,比如說顯示自定義類型的數(shù)據(jù),就需要另寫渲染衩侥,以及添加索引行国旷,移動數(shù)據(jù)、排序茫死、顯示圖片等等都不適合用這種方法跪但,而上面提到的在Table顯示圖片,移動數(shù)據(jù)峦萎、排序等內(nèi)容會在以后文章中陸續(xù)總結(jié)屡久。但是,如果只是用來顯示一些基礎(chǔ)類型的數(shù)據(jù)爱榔,不會對數(shù)據(jù)做動態(tài)操作被环,那么這種方法是完全夠用了。