Java setting column width and row height for jtable
In Java, you can set the column width and row height for a JTable
component using the setPreferredWidth
method of the TableColumn
class and the setRowHeight
method of the JTable
class.
Here's an example of how to do this:
refer to:theitroad.comimport javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; public class TableExample extends JFrame { private final JTable table; public TableExample() { super("Set Column Width and Row Height for JTable"); // Create a new table model with some data DefaultTableModel model = new DefaultTableModel(new Object[][]{ {"John", "Doe", 30}, {"Jane", "Doe", 25}, {"Bob", "Smith", 45}, {"Sally", "Johnson", 35}, }, new String[]{"First Name", "Last Name", "Age"}); // Create a new JTable with the table model table = new JTable(model); // Set the preferred width of the "First Name" column to 100 pixels TableColumn column = table.getColumnModel().getColumn(0); column.setPreferredWidth(100); // Set the preferred width of the "Last Name" column to 100 pixels column = table.getColumnModel().getColumn(1); column.setPreferredWidth(100); // Set the row height to 30 pixels table.setRowHeight(30); // Add the table to a scroll pane and the frame JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); // Set the size, location and visibility of the frame pack(); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new TableExample(); } }
In this example, we create a JTable
component and set its column width and row height using the setPreferredWidth
and setRowHeight
methods.
To set the preferred width of a column, we first get the TableColumn
object for the column using the getColumnModel
method of the JTable
class. We then call the setPreferredWidth
method on the column object and pass in the desired width in pixels.
To set the row height, we simply call the setRowHeight
method on the JTable
object and pass in the desired height in pixels.
When you run this example, a window will appear with a JTable
that has the first and last name columns set to 100 pixels and the row height set to 30 pixels.