我有一个JTable,我正在尝试在JTable后面插入一个图像作为水印
tblMainView= new JTable(dtModel){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer( renderer, row, column);
// We want renderer component to be transparent so background image is visible
if( c instanceof JComponent )
((JComponent)c).setOpaque(true);
return c;
}
ImageIcon image = new ImageIcon( "images/watermark.png" );
public void paint( Graphics g )
{
// First draw the background image - tiled
Dimension d = getSize();
for( int x = 0; x < d.width; x += image.getIconWidth() )
for( int y = 0; y < d.height; y += image.getIconHeight() )
g.drawImage( image.getImage(), x, y, null, null );
// Now let the regular paint code do it's work
super.paint(g);
}
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
public Class getColumnClass(int col){
if (col == 0)
{
return Icon.class;
}else if(col==7){
return String.class;
}
else
return String.class;
}
public boolean getScrollableTracksViewportWidth() {
if (autoResizeMode != AUTO_RESIZE_OFF) {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
}
return false;
}
};上面是我的JTable的代码,但水印是不可见的;让我补充一下,稍后我将这个JTable放在JScrollPane和JSplitPane中。
发布于 2011-07-20 22:48:06
两种可能的解决方案,但我不知道是哪一种。我认为第一种方法会有最高的成功机会。
第一种方法
重写您的paintComponent(Graphics g)方法:
public void paintComponent(Graphics g)
{
//First super
super.paintComponent(g);
g.drawImage(0, 0, getWidth(), getHeight());
}第二种方法
将JTable opaque设置为false:table.setOpaque(false);
重写您的paintComponent(Graphics g)方法:
public void paintComponent(Graphics g)
{
//First draw
g.drawImage(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}发布于 2011-07-20 22:28:28
有一些错误
在Swing JComponents中使用paint(Graphics g)确实不是一个好主意,paint()是用于AWT代码,对于Swing是否存在paintComponent(Graphics g),在Swing中使用paint(Graphics g)会在Swing GUI中显示意外的输出,
在任何Renderer中,用paint(Graphics g)编写AWT代码或用paintComponent(Graphics g)编写Swing代码都不是个好主意
您必须准备JTable的BackGroung,如这里的TableWithGradientPaint所示
发布于 2011-07-20 22:16:15
尝试在绘制水印之前调用super.paint(g),JTable可能正在覆盖您的图像。
https://stackoverflow.com/questions/6763368
复制相似问题