【问题标题】:JSlider getX(), getY() JAppletJSlider getX(), getY()
【发布时间】:2012-05-30 14:52:20
【问题描述】:

GUI 组件的位置、宽度和高度何时设置?如果正在使用布局管理器,这些字段如何影响?我有一个包含两个滑块的面板,我想在其中一个旁边绘制一个矩形。这是我的代码,用于初始化我的 GUI 组件并在其中一个滑块旁边用矩形绘制它们:

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。当我调整我的小程序的大小并因此导致它被重新绘制时,这些字段不再为零。为什么它们最初都是零?这是我的小程序类中的代码:

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

【问题讨论】:

    标签: java user-interface applet components init


    【解决方案1】:

    组件的位置和大小在渲染 GUI 时设置,在此之前它们是默认值 0。对于桌面应用程序,当在顶级窗口上调用 pack() 或在顶级窗口上调用 setVisible(true) 时发生这种情况.

    如果它是一个小程序,那么它是在小程序被渲染的时候——一些在幕后完成的事情。您可以使用其中一个 Swing 侦听器来侦听此内容。我必须查找哪个,可能是AncestorListener.... 编辑,是的,我认为这是正确的,尝试使用 AncestorListener。

    考虑购买Filthy Rich Clients 以获得一本深入了解 Swing 图形的精彩书籍。

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 2013-05-16
      • 2011-09-08
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多