Tag Archives: JTable

JTable Mastery: convertColumnIndexToModel

Study the code below. There is something wrong with it! Can you guess what it is?

public class JTableViewToModelColumn {
	public static void main(String[] args) {
		JFrame f = new JFrame("View To Model Column Example");

		final DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[]{"Col A", "Col B", "Col C"} );
		model.setRowCount(10);
		final JTable table = new JTable(model);

		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int col = table.columnAtPoint(e.getPoint());
				System.out.println("You click on column " + model.getColumnName(col));
			}
		});

		f.add(new JScrollPane(table), BorderLayout.CENTER);
		f.pack();
		f.setVisible(true);
	}
}

READ MORE »

How to format numbers in a JTable with a NumberCellRenderer

NumberCellRendererDemo

By default, the JTable show the cell values as regular text using a JLabel. To display numbers properly, you are force to pre-format the number as string values before setting them in the table model. There is a better way, by using your own implementation of TableCellRenderer. This will allow you to store the values in their intrinsic form inside the table model.

READ MORE »