Im trying to add a centered background image behind a JTable in a JScrollPane. The position of the background relative to the Viewport should be centered and static.
Ive tried adding the JScrollPane to a JPanel with a drawn image and making everything else translucent, but the result was ugly and had rendering issues.
Check out the WatermarkDemo at the end of the article for a complete example.
You should subclass JTable
and override its paint
method so that it draws your background image. Here is some sample code:
final JTable table = new JTable(10, 5) {
final ImageIcon image = new ImageIcon("myimage.png");
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
final Component c = super.prepareRenderer(renderer, row, column);
if (c instanceof JComponent){
((JComponent) c).setOpaque(false);
}
return c;
}
@Override
public void paint(Graphics g) {
//draw image in centre
final int imageWidth = image.getIconWidth();
final int imageHeight = image.getIconHeight();
final Dimension d = getSize();
final int x = (d.width - imageWidth)/2;
final int y = (d.height - imageHeight)/2;
g.drawImage(image.getImage(), x, y, null, null);
super.paint(g);
}
};
table.setOpaque(false);
final JScrollPane sp = new JScrollPane(table);
final JFrame f = new JFrame();
f.getContentPane().add(sp);
f.setSize(200,200);
f.setVisible(true);
Not sure if this is what you need, but have a look at the Substance Look and Feel which supports watermarks: https://substance.dev.java.net/docs/watermarks.html
来源:https://stackoverflow.com/questions/4791022/background-image-in-jscrollpane-with-jtable