Ask Your Question
2

What is the process for developing a JTable that has both row and column headers?

asked 2022-04-08 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-09 20:00:00 +0000

nofretete gravatar image

The process for developing a JTable with both row and column headers involves the following steps:

  1. Create a new JTable object.
  2. Create a new TableModel object which defines the data structure of the table.
  3. Specify the data for the row headers and column headers in two separate arrays.
  4. Create a new JScrollPane object which will hold the JTable and allow the user to scroll through it.
  5. Set the row header of the JScrollPane to a new JList object containing the row headers.
  6. Set the column header of the JTable to a new JTableHeader object containing the column headers.
  7. Add the JScrollPane to the main JFrame.

Example code:

String[] columnHeaders = {"Header1", "Header2", "Header3"};
String[][] data = {{"Row1 Data1", "Row1 Data2", "Row1 Data3"}, 
                   {"Row2 Data1", "Row2 Data2", "Row2 Data3"}, 
                   {"Row3 Data1", "Row3 Data2", "Row3 Data3"}};
String[] rowHeaders = {"Row1", "Row2", "Row3"};

TableModel tableModel = new DefaultTableModel(data, columnHeaders);
JTable table = new JTable(tableModel);

JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setRowHeaderView(new JList(rowHeaders));
table.setColumnModel(new JTableHeader(table.getColumnModel()));

frame.add(scrollPane);
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-08 11:00:00 +0000

Seen: 12 times

Last updated: Apr 09 '23