2012-05-24 105 views
1

何时是GUI组件的位置,宽度和高度设置?如果布局经理正在使用,这些领域是如何实现的?我有一个包含两个滑块的面板,我想在其中一个旁边画一个矩形。这里是我的代码初始化我的GUI组件和一个矩形画他们旁边的滑块之一:JSlider getX(),getY()JApplet

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()); 
} 

我发现,emSlider.getX(),emSlider.getY()的getWidth()和getHeight()最初都是0。当我调整我的小程序的大小,并因此导致它重新绘制时,字段不再为零。为什么他们最初都是零?这里是我的applet类代码:

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(); 
    } 

回答

1

组件位置和大小时,GUI渲染设置,在此之前,他们是默认值,0。对于桌面应用程序,在顶层窗口调用pack()时,或者在顶层窗口调用setVisible(true)时发生这种情况,或者在组件本身完成渲染后添加到GUI中时发生。

如果它是一个applet,那么它就是applet呈现的时候 - 这是在幕后完成的。您可以使用其中一个Swing侦听器来侦听此问题。我必须查找哪一个,可能是AncestorListener ....编辑,是的,我认为是正确的,请尝试使用AncestorListener。

考虑购买Filthy Rich Clients这本精彩的书籍将深入到Swing图形中。

相关问题