我需要将数据库的查询结果显示到JTable里面,表的首行为数据表的列名通过JTableHeader的方法来获取,现在可以实现将数据显示到table当中,但是由于数据比较多,table里面显示出来非常拥挤,我上网查了下利用JTable的setAutoResizeMode(JTable.AUTO_RESIZE_OFF)方法可以将下面的数据显示的不那么拥挤,但是对于数据项少的数据又显得很别扭,有很大一部分空白,尤其是当下面table显示的数据不那么拥挤的情况下当拖动下面的滚动条的时候表格内的数据会随着拖动向后显示,但是那个表头却不动。。这样就造成了数据对应错乱
而且表格中由于有些数据项内容比较多所以显示出来也不那么全
求问如何才能合理设计让这些数据显示完全的同时看起来也比较美观呢?Javajtablejtableheader数据库
而且表格中由于有些数据项内容比较多所以显示出来也不那么全
求问如何才能合理设计让这些数据显示完全的同时看起来也比较美观呢?Javajtablejtableheader数据库
这个我好像添加过了啊 具体我也不怎么清楚了。。因为这个是参考别人的代码写的。。public DataTableJScrollPane(final String[][] data, final String[] column) {
DataJTable table = DataJTable.getNewInstance();
// 在主面板创建数据表格时,每次都创建新的
table.setModel(new DefaultTableModel(data, column));
setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
setVerticalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
table.getTableHeader().setReorderingAllowed(false); //指定标题的重新排序是否被允许
table.getTableHeader().setResizingAllowed(false); //确信列不会因为在列标题之间拖动而改变大小
setViewportView(table);
}
class ProductModel extends AbstractTableModel{
Vector<YProduct> data=new Vector<YProduct>();
String[] columns={"编号","名称","计量单位","品牌","规格","分类","条形码","进价","批发价","零售价","数量"};
public ProductModel(Vector<YProduct> data){
this.data=data;
}
@Override
public int getRowCount() {
if(this.data==null)
return 0;
return this.data.size();
} @Override
public int getColumnCount() {
return columns.length;
} @Override
public Object getValueAt(int rowIndex, int columnIndex) {
YProduct product=data.get(rowIndex); String r="";
switch(columnIndex){
case 0:
r=product.getId();
break;
case 1:
r=product.getName();
break;
case 2:
if(product.getUnit()!=null)
r=product.getUnit();
break;
case 3:
if(product.getBrand()!=null)
r=product.getBrand();
break;
case 4:
if(product.getSpecification()!=null)
r=product.getSpecification();
break;
case 5:
if(PmsDictionary.getDesc("PMSPRODUCT", "CATEGORY", (byte)product.getCategory())!=null)
r=PmsDictionary.getDesc("PMSPRODUCT", "CATEGORY", (byte)product.getCategory());
break;
case 6:
if(product.getShapeCode()!=null)
r=product.getShapeCode();
break;
case 7:
if(product.getBidPrice()!=0)
r=product.getBidPrice()+"";
break;
case 8:
if(product.getTradePrice()!=0)
r=product.getTradePrice()+"";
break;
case 9:
if(product.getRetailPrice()!=0)
r=product.getRetailPrice()+"";
break;
case 10:
if(product.getCount()!=0)
r=product.getCount()+"";
break;
}
return r;
}
@Override
public String getColumnName(int column) {
return columns[column];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
这个重写不是针对你这个需求来写的, 如果你的表头要根据查询的结果来,那你就直接将表头用构造器去初始化就得了,而不是像列子一样直接在model里面写, 你直接把getValueAt,getColumnName,getRowCount以及getColumnCount方法改写一下就可以了,见其名知其意再结合例子你就知道怎么做了
另外之前我设置的基本上列宽就是相同的导致显示很拥挤,而且添加滚动条后只有竖的显示横的不显示,在使用了setAutoResizeMode(JTable.AUTO_RESIZE_OFF)后横的滚动条显示但是会出现表头不会跟着拖动而在另一台机子上测试的时候表头跟着动但是动着动着后面的表头显示就是一条很多表格合并的乱码
很是郁闷啊 ╮(╯▽╰)╭
如果你觉得设置成相同的列宽不合适的话那么你就每列每列的去设置好了, 也花不了多长时间。
至于你说的表头的问题,你好好检查一下代买,有可能是你的就table设置了尺寸,还有可能就是你的表头和你的数据有不一致的情况