2 Replies Latest reply on Oct 8, 2004 3:08 PM by 807587

    JTable HeaderRenderer With Image Resize

    807587
      Hey all, I have written a little class for a column renderer in my JTable its a JButton but without text just an Image. My problem is when the column is resized i would like the image to stretch. I tried adding a component listener to the button but since its a TableCellRenderer the componentResized method is never called. What can i do scale the image to the same size as the button everytime the column header is resized.

      Thanks

      M.L
        • 1. Re: JTable HeaderRenderer With Image Resize
          807587
          Here you go:
          public class TestHeaderRenderer extends JButton implements TableCellRenderer {
               private BufferedImage theImage;
          
               public TestHeaderRenderer() {
                    try {
                         theImage = ImageIO.read(TestHeaderRenderer.class.getResourceAsStream("/icons/next.gif"));
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
                    setIcon(new ImageIcon(theImage));
               }
          
               public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                                         boolean hasFocus, int row, int column) {
                    return this;
               }
          
               public void paint(Graphics g) {
                    setIcon(null);
                    super.paint(g);
                    Dimension dim = getSize();
                    Insets insets = getInsets();
                    int newImageWidth = dim.width - (insets.left + insets.right);
                    Graphics2D g2D = (Graphics2D)g;
                    g2D.translate(insets.left, insets.top);
                    AffineTransform xform = new AffineTransform();
                    double scale = (double)newImageWidth / (double)theImage.getWidth();
                    xform.scale( scale , 1.0);
                    g2D.drawImage(theImage, xform, null);
                    setIcon(new ImageIcon(theImage));
               }
          }
          You just have to make sure the path given in the constructor points to a valid icon file. Then add this column renderer to the desired column. Hope this helps and don't forget the dukes.
          • 2. Re: JTable HeaderRenderer With Image Resize
            807587
            thanks... works prety good