找到JTable单元并进行绘制 [英] Find the JTable cell and paint it

查看:76
本文介绍了找到JTable单元并进行绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些数据:

  1. 行号
  2. 列号
  3. 单元格值

我的问题是:

  1. 如何使用这些数据查找单元格?
  2. 如何在鼠标按下事件时将JTable单元格的背景更改为鼠标释放事件时的正常背景?
  3. 我可以在没有用户交互的情况下突出显示JTable吗,这意味着我可以通过使用给定的信息单击要突出显示另一个JTable单元格的其他JTable单元格吗?
  1. How can I find the cell by using those data?
  2. How can I change the background of JTable cell on mouse press event and back to normal background on mouse release Event?
  3. Can i Highlight the JTable without user interaction, means clicking on some other JTable cell i want to highlight another JTable cell by using given information, is it possible?

推荐答案

假设您要查找要进行点击检测的单元格的矩形:

Assuming you mean to find the rectangle of the cell for hit detection:

 Rectangle cell = table.getCellRect(row, column, false);

要更改背景,请在mouseListener代码中设置一个标记,单击哪个单元格,在按下/释放时重新绘制,并实现一个自定义渲染器以检查该标记.一些伪代码

For background changing, in your mouseListener code, set a marker which cell was hit, repaint on pressed/released and implement a custom renderer which checks for the marker. Some pseudo-code

 void mousePressed(MouseEvent ev) {
     // get the row/column from mouse location
     int column = table.columnAtPoint(ev.getPoint());
     int row = table.rowAtPoint(ev.getPoint());
     // set some kind of marker, f.i. as client property
     table.putClientProperty("hitColumn", column);
     table.putClientProperty("hitRow", row);
     // get the rectangle for repainting 
     Rectangle cell = table.getCellRect(column, row, false);
     table.repaint(cell);
 }

 void mouseReleased(MouseEvent ev) {
     // similar to reset the marker
     ....
     table.repaint(cell);
 }

 // custom renderer extends DefaultTableCellRenderer

 JComponent getTableCellRendererComponent(..., row, column ...) {
     Integer hitColumn = table.getClientProperty("hitColumn");
     Integer hitRow = ....
     if (hitColumn != null && column == hitColumn && hitRow ....) {
        setBackground(hitColor);
     } else {
         // force super to handle the background 
         setBackground(null);
     }
     return super.getTableCellRendererComponent(....);
 }

这篇关于找到JTable单元并进行绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆