Reputation: 305
I'm trying to create a program that displays a table with data on it, called a Time Log program. I'm having trouble expanding a Jtable to fill a JPanel, since it's currently looking like this:
You can see the huge white gap below the table, but I want the rows to be evenly distributed among the space.
Below is my code.
This is a class I call TimeLogApplication, which has main method and creates a JFrame.
public static void main(String[] args) {
/* Create a new frame */
JFrame guiFrame = new JFrame("Time Log Program");
/* Set size of the frame */
guiFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
/* Add the panel */
guiFrame.add(new TimeLogPanel());
/* Exit normally on closing the window */
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Show the frame */
guiFrame.setVisible(true);
}
The JFrame calls TimeLogPanel class that creates a JPanel. This panel has a Border Layout. The table is added to the center panel, which also has Border Layout.
public TimeLogPanel() {
// Set layout, add table panel
setLayout(new BorderLayout(20, 20));
add(tablePanel);
// Create table panel and set layout
tablePanel = new JPanel();
tablePanel.setLayout(new BorderLayout());
// Create a new table with row and column number
table = new JTable(rowNum, colNum);
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
// Set a raised border
table.setBorder(new EtchedBorder(EtchedBorder.RAISED));
// Add table to table panel
tablePanel.add(table);
}
I have tried to get the panel height but since it is not created until the frame is created, the panel height is zero.
Thanks in advance for any suggestions!
UPDATE: I tried out the suggestions and it worked beautifully (adding ComponentListener to the JPanel that holds the JTable). This is what I did:
tablePanel.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
tablePanelSize = tablePanel.getHeight();
table.setRowHeight(tablePanel.getHeight()/rowNum); //RowNum is the number of rows
}
// Below methods are not used but must be there, as a requirement when adding a listener
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
});
Upvotes: 2
Views: 1169
Reputation: 1110
I think you have to add a ComponentListener
(componentResized
event), calculate the row height and then call JTable.setRowHeight
.
Upvotes: 3