When is a GUI component’s position, width and height set? If layout managers are being used, how are these fields effected? I have a panel that contains two sliders and I want to draw a rectangle next to one of them. Here is my code to initialize my GUI components and paint them with a rectangle next to one of the sliders:
public PhotoSliders()
{
initComponents(); //from the netbeans GUI designer
}
public void setColorRect() //initialize a colored rectangle
{
colorRect = new ColorRect(Color.RED, (double)(emSlider.getX())/getWidth(), (double)(emSlider.getY())/getHeight());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
colorRect.paintColorRect(g, getWidth(), getHeight());
}
I have found that the emSlider.getX(), emSlider.getY(), getWidth(), and getHeight() are all 0 initially. When I resize my applet and thus causing it to be repainted, the fields are no longer zero. Why are they all zero initially? Here is the code in my applet class:
public void init() //initialize the Applet Class
{
setLayout(new BorderLayout());
slidersPanel = new PhotoSliders();
JPanel north = new JPanel(new BorderLayout());
north.add(slidersPanel, BorderLayout.WEST);
add(north, BorderLayout.NORTH);
add(photoEffect, BorderLayout.CENTER);
slidersPanel.setColorRect();
}
public void paint(Graphics g) //paint the photoEffect
{
super.paint(g);
slidersPanel.setColorRect();
}
A component’s location and size are set when the GUI is rendered, and before that they are the default value,
0. For a desktop applicaiton, this occurs when eitherpack()is called on the top level window, or whensetVisible(true)is called on the top level window, or on the component itself if it is added to the GUI after all has been rendered.If it’s an applet, then it’s when the applet is rendered — something that is done behind the scenes. You may be able to listen for this using one of the Swing listeners. I have to look up which one, possibly an AncestorListener…. edit, yes I think that’s right, try using an AncestorListener.
Consider buying Filthy Rich Clients for a wonderful book that goes into great depths on Swing graphics.