Hello, I made a component called GradientLegend but I am having trouble to properly display it on a JFrame. The component is painted and immediately after disappears, leaving the frame empty (at least that's what happens when I compile and run the code below with java 1.4.1 for linux). By the tutorials I've been through the code seems to be right, does anyone find what's wrong? The code follows. Thanks.
Hi, Welcome to JavaRanch! I'm not sure why you're passing in the x,y location of the component as constructor parameters; in any case, the problem is that these are wrong as soon as the container is laid out. The wrong coordinates lead to the image being drawn in an offscreen location, so you can't see it. Instead of passing in x, y, use getLocation().x and getLocation().y in paintComponent(). You should find that your program works perfectly.
Thanks for your help, I just found out what the problem was. I use x and y as parameters for the caller to decide where does it want to show the gradient. In the paintComponent() method I was increasing y all the time, and when the component was repainted (which seems to happen right after the first paint), y was greater then the component height. I set y to it original value at the end of paintComponent() and now it works fine. By the way, how do I become something better than a greenhorn?
author and iconoclast
You automatically get to be a "ranch hand" after you've posted some number of times -- 30 times, I think? If you want something more colorful than that, you can either work very hard and be elected a bartender... or you can take the easy way out!