Skip to content

Commit

Permalink
fix: JTable#doLayout() is not called even if changing the height of J…
Browse files Browse the repository at this point in the history
…ScrollPane
  • Loading branch information
aterai committed Dec 8, 2017
1 parent 577951d commit 5dbb615
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions AdjustRowHeightFillsViewport/src/java/example/MainPanel.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,18 @@ public class MainPanel extends JPanel {
}
};
private final JTable table = new JTable(model) {
int prevHeight = -1;
int prevCount = -1;
private int prevHeight = -1;
private int prevCount = -1;
private void updateRowsHeight(JViewport vport) {
int height = vport.getExtentSize().height;
int rowCount = getModel().getRowCount();
int defautlRowHeight = height / rowCount;
if ((height != prevHeight || rowCount != prevCount) && defautlRowHeight > 0) {
int over = height - rowCount * defautlRowHeight;
for (int i = 0; i < rowCount; i++) {
int a = over-- > 0 ? i == rowCount - 1 ? over : 1 : 0;
int a = over > 0 ? i == rowCount - 1 ? over : 1 : 0;
setRowHeight(i, defautlRowHeight + a);
over--;
}
}
prevHeight = height;
Expand All @@ -42,20 +43,27 @@ private void updateRowsHeight(JViewport vport) {
Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, this))
.filter(clz::isInstance).map(clz::cast)
.ifPresent(this::updateRowsHeight);
// Container p = SwingUtilities.getAncestorOfClass(JViewport.class, this);
// if (p instanceof JViewport) {
// updateRowsHeight((JViewport) p);
// }
}
};
private final JScrollPane scroll = new JScrollPane(table);
private final JButton button = new JButton("add");

public MainPanel() {
super(new BorderLayout());

JScrollPane scroll = new JScrollPane(table);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.addComponentListener(new ComponentAdapter() {
@Override public void componentResized(ComponentEvent e) {
Component c = e.getComponent();
if (c instanceof JScrollPane) {
((JScrollPane) c).getViewport().getView().revalidate();
}
}
});

JButton button = new JButton("add");
button.addActionListener(e -> model.addRow(new Object[] {"", 0, false}));

add(scroll);
add(button, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
Expand Down

0 comments on commit 5dbb615

Please sign in to comment.