如何解决如何恢复JTable中的列宽?
我的问题很明确。用户调整大小后,是否可以自动恢复列的宽度?
每次单击按钮时,我都希望恢复列宽。
public class TableTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JTable table = new JTable(new Object[][] { { "something","something else" } },new Object[] { "Col1","Col2" });
table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
label.setForeground(Color.GREEN);
return label;
}
});
frame.add(new JScrollPane(table),BorderLayout.CENTER);
JButton button = new JButton("Button");
button.addActionListener(e -> {
// Restore column widths here
});
frame.add(button,BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
}
我尝试过:
table.setAutoCreateColumnsFromModel(false);
table.setAutoCreateColumnsFromModel(true);
但是它将删除渲染器。
我尝试过:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
但是什么也没做。
我尝试过:
for (int col = 0; col < table.getColumnCount(); col++) {
table.getColumnModel().getColumn(col).sizeWidthToFit();
}
机器人什么也不做。
有办法吗?还是我必须自己计算,然后getColumnModel.getColumn(..).setPreferredWidth(..)
?
解决方法
您需要自己进行管理。
默认情况下,宽度设置为75,因此您只需将宽度重置为75。
或者您可以在GUI可见后始终查询列的宽度。然后根据此值恢复宽度。
没有默认功能以原始宽度显示列
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。