EDIT: I know its posted as already answered but im having trouble with those solutions too.
I want a JTable that displays some SQL data in my application. I'm a beginner, but using the powers of google i've written the following code;
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)
{
}
}
The problem i have with this is the way the table looks.
You see the columns aren't displaying all the data. How do I adjust the size of the table so that the columns display all the data?
I've tried using the following method from another question, but i still get the same result what I pass table through it. I'm probably being dumb, but what input would go in the argument for vColIndex & margin...
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);
}
Ive also tried this from the same post... Still no luck
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);
}
}
Thanks in advance :)