How to programmatically set combobox width?
Hi,
Newbie in Java testing database access.
Succeeded to load driver, make a connection and reading tablenames.
Want to load retrieved tablenames into a jcombobox and afterwards adjust
combobox width to show even the table with longest name.
Tried this code:
Code Java:
private void getTables(Connection conn) throws SQLException
{
DatabaseMetaData dbmd = conn.getMetaData();
FontMetrics fm = cbxTableNames.getFontMetrics(cbxTableNames.getFont());
int maxw, w;
maxw = 0;
String[] types = {"TABLE"};
ResultSet tables = dbmd.getTables(null, null, null, types);
while (tables.next())
{
String tablename = tables.getString("TABLE_NAME");
w = fm.stringWidth(tablename);
if (maxw < w)
{ maxw = w;
}
cbxTableNames.addItem(tablename);
}
cbxTableNames.setVisible(true);
lblTableNames.setVisible(true);
cbxTableNames.setSize(new Dimension(maxw, 20));
}
Last statement:cbxTableNames.setSize(new Dimension(maxw, 20)); doesn't change the combobox width
but adding a separate jButton and in its' ActionPerformed event executing:
cbxTableNames.setSize(new Dimension(300, 20)) changes the with.
Why and how can I achieve desired effect?
Regards
stab:confused:
Re: How to programmatically set combobox width?
Try setPreferredSize(Dimension preferredSize) method instead.