Friday, November 26, 2010

Working with JTables

With JTables you can display tables of data, allowing the user to edit the data. Fallow this example if you want to learn how to fill a specific position in a JTable.
  • Create a new JDialog Form.
  • Drag and drop the JTable swing component into the JDialog Form. You should have something like this,

  • Next, change from Design View to Source View and paste the following source-code inside the constructor (after InitComponents),
jTable1.setValueAt("0,0 position", 0, 0);
jTable1.setValueAt("1,0 position", 1, 0);
jTable1.setValueAt("2,0 position", 2, 0);
jTable1.setValueAt("3,0 position", 3, 0);

jTable1.setValueAt("1,2 position", 1, 2);
jTable1.setValueAt("1,3 position", 1, 3);
  • Each line fills the first position of the table. Very simple :) Now, let's complicate a little more by changing the header font to bold. First, let's find out JTable's font by doing this,
Font font = jTable1.getTableHeader().getFont();
  • And now, change the font to bold,
jTable1.getTableHeader().setFont(font.deriveFont(Font.BOLD));

  • Resizing the column header you ask ... no problem, simply do this,
TableColumn column = null;
column = jTable1.getColumnModel().getColumn(1);
column.setPreferredWidth(140);
  • Run your file (Shift+F6), and you should have something like this,


Want to know more ? Read How to Use Tables.
Need help with something related ? Ask away :)

No comments:

Post a Comment