我想要一个在我的应用程序中显示一些SQL数据的JTable。我是初学者,但使用谷歌的权力我写了以下代码;
try
{
Statement st = ConnectionUtility.getConnection().createStatement();
ResultSet rs = st.executeQuery("SELECT c.aname, c.telephone_number, c.address, "
+ "p.sku_code, p.appliance_type, p.colour, p.ticket_price "
+ "FROM customers c "
+ "INNER JOIN products p "
+ "ON c.sales_number = p.sales_number");
JTable table = new JTable(buildTableModel(rs));
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
catch(Exception e)
{
}
}
我遇到的问题是表的外观。
您会看到列未显示所有数据。如何调整表的大小以使列显示所有数据?
我尝试过从另一个问题中使用以下方法,但我仍然得到了与我通过表格相同的结果。我可能很愚蠢,但是对于vColIndex&保证金......
public static void packColumn(JTable table, int vColIndex, int margin) {
DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width = 0;
// Get width of column header
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
java.awt.Component comp = renderer.getTableCellRendererComponent(
table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
// Get maximum width of column data
for (int r=0; r<table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(
table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
// Add margin
width += 2*margin;
// Set the width
col.setPreferredWidth(width);
}
我也在同一篇文章中试过这个......仍然没有运气
JTable table = new JTable(buildTableModel(rs));
JOptionPane.showMessageDialog(null, new JScrollPane(table));
for(int col = 0; col < table.getColumnCount(); col++)
{
int width = 0;
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer renderer = table.getCellRenderer(row, col);
Component comp = table.prepareRenderer(renderer, row, col);
width = Math.max (comp.getPreferredSize().width, width);
}
}
提前致谢:)