如何聚焦 JTable 的整行?
我有一个 JTable
,它显示 Java Swing 应用程序中的一些记录。用户只能处理整行,而不是单个单元格。有什么方法可以让我专注于 JTable 的整行吗?默认设置是仅聚焦用户单击的单元格。我使用不同的颜色作为焦点,因此如果只有一个单元格而不是整行获得焦点,效果看起来不太好。
更新:这是我的自定义TableCellRenderer
的当前代码,问题是当一行具有焦点并用“焦点”颜色绘制时,然后JTable
失去焦点,只有具有焦点的单元格 会使用“选定”颜色重新绘制,但选定行中的所有单元格都应使用“选定”颜色重新绘制。
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
// Has any cell in this row focus?
if(table.getSelectedRow() == row && table.hasFocus()) {
hasFocus = true;
}
if (hasFocus) {
this.setBackground(CustomColors.focusedColor);
} else if (isSelected) {
this.setBackground(CustomColors.selectedColor);
} else {
// alternate the color of every second row
if(row % 2 == 0) {
this.setBackground(Color.WHITE);
} else {
this.setBackground(CustomColors.grayBg);
}
}
setValue(value);
return this;
}
I have a JTable
that is showing some records in a Java Swing application. The user only works with whole rows, not with individual cells. Is there any way I can focus on a whole row of a JTable
? The default is to focus only the cell that the user has clicked on. I use a different color for the focus, so it doesn't look good if only a cell is focused instead of the whole row.
UPDATE: This is my current code of my custom TableCellRenderer
, the issue is that when a row has focus and is painted with the "focus" color, and then the JTable
loses focus, only the cell that had focus is repainted with the "selected" color but all cells in the selected row should be repainted with the "selected" color.
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
// Has any cell in this row focus?
if(table.getSelectedRow() == row && table.hasFocus()) {
hasFocus = true;
}
if (hasFocus) {
this.setBackground(CustomColors.focusedColor);
} else if (isSelected) {
this.setBackground(CustomColors.selectedColor);
} else {
// alternate the color of every second row
if(row % 2 == 0) {
this.setBackground(Color.WHITE);
} else {
this.setBackground(CustomColors.grayBg);
}
}
setValue(value);
return this;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您正在寻找setRowSelectionAllowed()
方法。既然您说仅更改颜色就足够了,您可能需要查看 Swing 教程的自定义单元格渲染器部分。您只需设置逻辑来检查给定单元格是否位于所选行中,并相应地绘制背景颜色。
Sounds like you're looking for thesetRowSelectionAllowed()
method.Since you said just changing the color would be sufficient, you might want to look at the custom cell renderer section of the Swing Tutorial. You'd just have to set the logic to check on whether a given cell was in a selected row, and paint the background color accordingly.
第一个想法是
我使用自己的逻辑仅根据行属性来确定焦点。它使用底层单元格渲染器,但如果使用焦点边框,看起来会很奇怪。
A first idea would be something like
where I use my own logic to determine the focus based on the row attribute only. It uses the underlying cell renderers but looks strange if focus border is used.