如何在 Java 中编辑 DefualtTableCellRenderer?
我在编辑 DefaultTableCellRenderer
时遇到问题。
我想右对齐表格中的第二列。然而,下面的代码右对齐所有列,而不仅仅是第二列!
谁能看到我哪里出错了?
for (int i=0; i < tblMenu.getModel().getColumnCount(); i++)
{
DefaultTableCellRenderer renderer =
(DefaultTableCellRenderer) tblMenu.getCellRenderer(i, 1);
renderer.setHorizontalAlignment(JTextField.RIGHT);
}
I am having a problem with editing the DefaultTableCellRenderer
.
I would like to right align just the 2nd column in my table. However, the code below right aligns all the columns, and not just the 2nd one!
Can anyone see where I am going wrong?
for (int i=0; i < tblMenu.getModel().getColumnCount(); i++)
{
DefaultTableCellRenderer renderer =
(DefaultTableCellRenderer) tblMenu.getCellRenderer(i, 1);
renderer.setHorizontalAlignment(JTextField.RIGHT);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用匿名内部类覆盖表上的默认渲染器。类似以下(未经测试)的代码可能会起作用:
You can override the default renderer on your table with an anonymous inner class. Something like the following (untested) code might work:
默认情况下,所有列都使用相同的渲染器,您需要为要更改的列提供不同配置的渲染器:
也许比 A Lee 的方式简单一点(取决于您正在执行多少其他自定义操作)。
All columns use the same renderer by default, you need to provide a differently configured one for the column you want to change:
Maybe a little simpler than A Lee's way (depending on how much other customization you're doing).
您可以为特定列设置单元格渲染器。您所要做的就是获取表的columnModel,然后获取特定列,然后为该列调用setCellRenderer。
但更简单的是,如果您的列包含数字数据,只需覆盖表模型的
getColumnClass(...)
即可返回该列的 Integer.class,并且表将为您正确设置格式。或者,如果您知道您的表不会为空,只需让表的数据告诉世界它是什么类型,并让 JTable 以最佳方式呈现内容:You can set the cell renderer for a specific column. All you have to do is get the table's columnModel, then get the specific column, then call setCellRenderer for that column.
But even easier, if your column holds numeric data, simply override the table model's
getColumnClass(...)
to return Integer.class for that column and the table will format correctly for you. Or if you know your table will not be empty, simply let the table's data tell the world what type of type it is and let the JTable render things as best it should: