我在书上看到一段点BUTTON改变布局的代码:
1.
public class flowlayoutframe extends JFrame
{
   ...
   Private FlowLayout layout;
   ...
   container = getContentPane();
   ..
   btn.addActionListener 
   {
       new ActionListener()
       { ...
        layout.setAlignment(FlowLayout.CENTER);
        layout.layoutContainer(container);}
   }
}
我想问 为什么这里不能用container.setLayout(layout)呢?2. 还有就是有时候看到set Jframe layout是直接在Frame的构造函数中setLayout(layout),有时候又是先getContentPane()给container,然后container.setLayout ,请问怎么解释?谢谢!

解决方案 »

  1.   

    flowlayoutframe 继承了JFrame,JFrame有setLayout方法。
    所以直接用setLayout就是设置flowlayoutframe的布局。flowlayoutframe.getContentPane()得到 flowlayoutframe下的container容器,调用container的setLayout方法是设置container的布局。
      

  2.   

    谢谢!
    1. 你所说的设置JFrame 布局 和 JFrame 下容器的布局,有什么区别吗,换句话说,我什么地方必须要先获取容器container?2. 在第一段代码中,是否可以吧layout.layoutContainer(container)改成container.setLayout(layout)?后者不是更符合我们的理解习惯么,为什么书上习惯用调用Layout Manager的layoutContainer方法去告知Frame布局变了呢?
      

  3.   

    flowlayoutframe 是房子,flowlayoutframe.getContentPane() 是这个房子内的一个桌子。
    把房子的布局弄好了,桌子上东西也要摆摆。等于布局有了一个风格,可以用到很多容器上去;且可以在容器外去设置,更换布局也方便。
    container.setLayout(layout)局限在容器内去调用,耦合性稍高;更换布局还要去容器那修改代码。
    作用应该是一样,只是前一种编码风格上更好。
      

  4.   

    JFrame中是重写了Container中的setLayout()方法。JFrame的构成:
    从底层而上:RootPane -- LayerredPane -- ContentPane -- GlassPane
    这些面板都可以直接放在JFrame框架内。JFrame是基于AWT模拟而成,一个JFrame框架必须包含一个Pane,然后再在Pane中添加各种组件。每个Pane中可以使用不同的布局管理器。比如new JPanel()默认就使用FlowLayout布局管理器,而JFrame或者RootPane 中默认使用BorderLayout布局管理器,如果取消布局管理器,则必须声明setLayout(null),然后使用setBounds()为各个组件设置位置和大小。
      

  5.   

    恩 有道理 谢谢。 我试了试,发现container.setLayout(layout);也是一样作用的,不过后面得用上 container.validate();
      

  6.   


    layout.layoutContainer() 这个方法,不是让你直接调用的当布局内的控件有改动或布局器的属性有改动时,为了让布局器重算控件大小和位置,让container重绘,推荐调用的方法是container.revalidate();