java jtable组件,Java如何为JTable组件创建表模型?

创建和配置JTable组件的另一种方法是使用表模型。表模型比使用数组或向量作为表的数据源更可取。

创建表模型的最简单方法是扩展AbstractTableModel实现该TableModel接口的抽象类。该AbstractTableModel工具实现表模型的标准行为。它实现了TableModel接口的几乎所有方法,除了三种方法。

这三种方法分别是getValueAt(int rowIndex, int columnIndex)方法,getRowCount()方法和getColumnCount()方法。下面的代码向您展示如何创建表模型。package org.nhooo.example.swing;

import javax.swing.*;

import javax.swing.table.AbstractTableModel;

import java.awt.*;

public class TableModelDemo extends JPanel {

public TableModelDemo() {

initializePanel();

}

private void initializePanel() {

// 创建PremiereLeagueTableModel的实例

PremiereLeagueTableModel tableModel =

new PremiereLeagueTableModel();

// 使用TableModel创建JTable的实例

// 作为构造函数参数。

JTable table = new JTable(tableModel);

table.setFillsViewportHeight(true);

JScrollPane scrollPane = new JScrollPane(table);

this.setPreferredSize(new Dimension(500, 200));

this.setLayout(new BorderLayout());

this.add(scrollPane, BorderLayout.CENTER);

}

public static void showFrame() {

JPanel panel = new TableModelDemo();

panel.setOpaque(true);

JFrame frame = new JFrame("Premiere League - 2018/2019");

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

frame.setContentPane(panel);

frame.pack();

frame.setVisible(true);

}

class PremiereLeagueTableModel extends AbstractTableModel {

// TableModel的列名

private String[] columnNames = {

"TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"

};

// TableModel的数据

private Object[][] data = {

{ "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },

{ "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },

{ "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },

{ "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },

{ "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }

};

/**

* Returns the number of rows in the table model.

*/

public int getRowCount() {

return data.length;

}

/**

* Returns the number of columns in the table model.

*/

public int getColumnCount() {

return columnNames.length;

}

/**

* Returns the column name for the column index.

*/

@Override

public String getColumnName(int column) {

return columnNames[column];

}

/**

* Returns data type of the column specified by its index.

*/

@Override

public Class> getColumnClass(int columnIndex) {

return getValueAt(0, columnIndex).getClass();

}

/**

* Returns the value of a table model at the specified

* row index and column index.

*/

public Object getValueAt(int rowIndex, int columnIndex) {

return data[rowIndex][columnIndex];

}

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

showFrame();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值