1. 方法 1
不提供任何数据, 也不创建列和行.
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
不提供任何数据, 但是创建列和行.
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
从图中可以很容易地发现一个有意思的地方, 那就是表的列头竟然是 ABC, 因为我们是没有提供表头的, 那么如果把当前的 3 列改为 27, 会怎么样呢?
方法二效果 - 2
通过上面两张图, 可以很明显的得出一个结论, 就是在我们没有提供列头的情况下, Java 会默认提供列头. 但是这种情况, 很明显不是我们想要的显示结果.
3. 方法 3
提供数据 (单元格内容和列头) 并且创建列和行.
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 效果
方法三效果
这种方法是一般最常用的方法, 也是最基础最简单的方法, 但正因为最基础, 所以有很大局限性, 比如说显示自定义类型的数据, 就需要另写渲染, 以及添加索引行, 移动数据, 排序, 显示图片等等都不适合用这种方法, 而上面提到的在 Table 显示图片, 移动数据, 排序等内容会在以后文章中陆续总结. 但是, 如果只是用来显示一些基础类型的数据, 不会对数据做动态操作, 那么这种方法是完全够用了.
来源: http://www.jianshu.com/p/7a0630d903bd