importjava.awt.BorderLayout;importjava.awt.Color;importjava.util.Vector;importjavax.swing.JFrame;importjavax.swing.JScrollPane;importjavax.swing.JTable;importjavax.swing.ListSelectionModel;importjavax.swing.table.DefaultTableCellRenderer;importjavax.swing.table.JTableHeader;importjavax.swing.table.TableCellRenderer;publicclassJTableDefineTestextendsJFrame{publicJTableDefineTest()
{super();
setTitle("表格");
setBounds(100,100,500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane=newJScrollPane();//支持滚动getContentPane().add(scrollPane,BorderLayout.CENTER);
String[] columnNames={"A","B","C","D","E","F","G"};
Vector columnNameV=newVector();//获得表头for(intcolumn=0;column
{
columnNameV.add(columnNames[column]);
}
Vector tableValueV=newVector();for(introw=1;row<21;row++)//获得数据{
Vector rowV=newVector();for(intcolumn=0;column
{
rowV.add(columnNames[column]+row);//数据}
tableValueV.add(rowV);
}
JTable table=newMyTable(tableValueV,columnNameV);//自定义的表格table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//关闭表格列的自动调整功能。table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//单选table.setSelectionBackground(Color.YELLOW);
table.setSelectionForeground(Color.RED);
table.setRowHeight(30);
scrollPane.setViewportView(table);//支持滚动}/***@paramargs*/publicstaticvoidmain(String[] args) {//TODO Auto-generated method stubJTableDefineTest jTableDefineTest=newJTableDefineTest();
jTableDefineTest.setVisible(true);
}
}classMyTableextendsJTable//实现自定义类{/****/privatestaticfinallongserialVersionUID=1L;publicMyTable()
{
}publicMyTable(Vector rowData ,Vector columnNames)
{super(rowData,columnNames);
}/*** @Override*/publicJTableHeader getTableHeader()
{
JTableHeader tableHeader=super.getTableHeader();
tableHeader.setReorderingAllowed(false);//设置表格列不可重排DefaultTableCellRenderer hr=(DefaultTableCellRenderer)tableHeader.getDefaultRenderer();//获得表格头的单元格对象hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//列名居中returntableHeader;
}/*** @Override*/publicTableCellRenderer getDefaultRenderer(Class>columnClass)
{
DefaultTableCellRenderer cr=(DefaultTableCellRenderer)super.getDefaultRenderer(columnClass);
cr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);//单元格内容居中returncr;
}/*** @Override*/publicbooleanisCellEditable(introw,intcolumn)
{returnfalse;//单元格不可修改}
}