use*_*020 13 java swing jtable preferredsize jviewport
我需要在JScrollPane中创建一个带有可调整大小的列的JTable(当用户增加列宽时 - 出现水平滚动条).为此,我有用table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);.此外,当视口宽度足以包含整个表格时 - 列应该拉伸以填充视口宽度.为了实现这一点,我有getScrollableTracksViewportWidth()JTable类的覆盖方法如下:
@Override
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
Run Code Online (Sandbox Code Playgroud)
这种方法很有效,除了一件事:当我第一次尝试调整列的大小时,它返回自己的宽度以开始位置.如果我快速调整列大小并释放鼠标表继续工作正常.那么,这种行为的原因是什么?为什么表尝试调整大小,即使getScrollableTracksViewportWidth()返回false?或者,也许,你可以提出更好的解决方案来实现这样的调整大小模式?
贝娄是上述问题的简单工作示例:
import javax.swing.*;
public class TestTable {
private static Object[][] data = new Object[][] {
{ "a", "b", "c" },
{ "d", "e", "f" }
};
private static Object[] colNames = new Object[] { "1", "2", "3" };
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTable table = new JTable(data, colNames) {
@Override
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
cam*_*ckr 17
doLayout()当水平滚动条不可见时,当你试图增加列的大小时似乎默认逻辑不起作用,所以我摆脱了默认逻辑并且只是接受了列的宽度而没有尝试调整它.
import javax.swing.*;
import javax.swing.table.*;
public class TestTable {
private static Object[][] data = new Object[][] {
{ "a", "b", "c" },
{ "d", "e", "f" }
};
private static Object[] colNames = new Object[] { "1", "2", "3" };
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTable table = new JTable(data, colNames)
{
@Override
public boolean getScrollableTracksViewportWidth()
{
return getPreferredSize().width < getParent().getWidth();
}
@Override
public void doLayout()
{
TableColumn resizingColumn = null;
if (tableHeader != null)
resizingColumn = tableHeader.getResizingColumn();
// Viewport size changed. May need to increase columns widths
if (resizingColumn == null)
{
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
super.doLayout();
}
// Specific column resized. Reset preferred widths
else
{
TableColumnModel tcm = getColumnModel();
for (int i = 0; i < tcm.getColumnCount(); i++)
{
TableColumn tc = tcm.getColumn(i);
tc.setPreferredWidth( tc.getWidth() );
}
// Columns don't fill the viewport, invoke default layout
if (tcm.getTotalColumnWidth() < getParent().getWidth())
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
super.doLayout();
}
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
编辑使用AUTO_RESIZE_ALL_COLUMNS.