固定JTable中的前几列
2009-09-23 00:00:00 来源:WEB开发网图片看不清楚?请点击这里查看原图(大图)。
图三
主要实现代码分析,实现主要监听鼠标事件,捕捉所要固定的列的内容予以即时更新,这个类FixTableManager为了方便我们继承于JTableHeader,那么在这里我们重写paint()方法:以更新拖动Scrollbar的时候列头的现实信息,代码如:
@Override
public void paint(Graphics g) {
super.paint(g);
//int division = mouseListener.getDivision();
int division = mouseListener.getDivision();
if (division > 0){
Rectangle r = getVisibleRect();
BufferedImage image = new BufferedImage(division, r.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g2 = image.getGraphics();
g2.setClip(0, 0, division, r.height);
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, division, r.height);
super.paint(g2);
g.drawImage(image, r.x, r.y, division, r.height, null);
g2.dispose();
}
}
画完了固定的列的列头,我们就要画表格中的内容了,这里我们就是把这些内容画在一个JLabel上,如下:
private class FixedColumnsDelegate extends JLabel{
public void paintComponent(Graphics g) {
Rectangle r = table.getBounds();
if (division > 0) {
table.invalidate();
table.validate();
Rectangle visibleRect = table.getVisibleRect();
BufferedImage image = new BufferedImage(division, r.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g2 = image.getGraphics();
g2.setClip(0, visibleRect.y, division,
table.getBounds().height);
g2.setColor(Color.RED);
g2.fillRect(0, 0, division, table.getBounds().height);
table.paint(g2);
g.drawImage(image, 0, 0, division,
table.getBounds().height, 0, visibleRect.y,
division, visibleRect.y + table.getBounds().height,
null);
// g.setColor(Color.BLACK);
// for (int i = 0; i < visibleRect.y
// + table.getBounds().height; i += 8) {
// g.drawLine(division - 1, i, division - 1, i + 4);
// g.drawLine(division - 2, i, division - 2, i + 4);
// }
g2.dispose();
}
}
}
更多精彩
赞助商链接