2011-08-24 23 views
2

我需要創建一個由JPanel使用的自定義LayoutManager。JPanel不會調用自定義LayoutManager的addLayoutComponent()

然而,當我將組件添加到JPanel中,JPanel的不叫我的自定義佈局管理的addLayoutComponent方法()方法,即使它應該:
http://download.oracle.com/javase/tutorial/uiswing/layout/custom.html

(它不會調用layoutContainer() ,如預期)

希望有人能告訴我我做錯了什麼。
如何讓JPanel調用addLayoutComponent()?

import java.awt.*; 
import javax.swing.*; 

public class Test 
{ 
    public static void main(String[] args) 
    { 
     createAndShowGUI(); 
    } 



    private static void createAndShowGUI() 
    { 
     JButton button = new JButton("Test"); 
     button.setBounds(64, 64, 128, 64); 

     JPanel panel = new JPanel(new CustomLayoutManager()); 

     //FIXME: Missing call to CustomLayoutManager.addLayoutComponent() 
     panel.add(button); 

     JFrame frame = new JFrame("Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(640, 480); 
     frame.add(panel); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
     frame.toFront(); 
    } 



    public static class CustomLayoutManager implements LayoutManager 
    { 
     public void addLayoutComponent(String name, Component comp) 
     { 
      System.out.println("addLayoutComponent"); 
     } 

     public void layoutContainer(Container parent) 
     { 
      System.out.println("layoutContainer"); 
     } 

     public Dimension minimumLayoutSize(Container parent) 
     { 
      System.out.println("minimumLayoutSize"); 
      return new Dimension(); 
     } 

     public Dimension preferredLayoutSize(Container parent) 
     { 
      System.out.println("preferredLayoutSize"); 
      return new Dimension(); 
     } 

     public void removeLayoutComponent(Component comp) 
     { 
      System.out.println("removeLayoutComponent"); 
     } 
    } 
} 

回答

3

我如何獲得的JPanel調用addLayoutComponent方法()?

如果你的佈局管理器使用限制

它只會調用這個方法
panel.add(button); 

嘗試:

panel.add("some constraint value", button); 

這種方法的目的是用來約束傳遞給佈局管理器。我認爲BorderLayout是唯一可能使用過的佈局管理器。但它通常不應該再使用。相反,LayoutManager2使用:

public void addLayoutComponent(Component component, Object constraint) 

它允許您傳遞任何對象作爲約束。

+0

非常感謝這個簡潔的答案。 看起來唯一「穩定」的方法是實現LayoutManager2。使用Container.add(Component component,Object constraint),根據需要調用LayoutManager2.addLayoutComponent(Component component,Object constraint)方法。 – Meyer

+0

問題是否有約束和putProperty之間的一些不同之處(我用於DocumentListener),當然也許我的問題是不符合實際的(缺少關於...的知識)+1 – mKorbel

+0

@mKorbel,約束是使用的對象由佈局經理幫助控制組件的佈局。有關如何使用約束的示例,請參閱GridBagLayout和GridBagConstraints。我不確定在DocumentListener或LayoutManager中使用了putProperty(),所以我不確定你在問什麼。 – camickr

相關問題