开发者

JPanel doesn't call addLayoutComponent() of custom LayoutManager

开发者 https://www.devze.com 2023-03-30 06:03 出处:网络
I need to create a custom LayoutManager to be used by a JPanel. However, when I add a Component to the JPanel, the JPanel doesn\'t call the addLayoutComponent() method of my custom LayoutManager, eve

I need to create a custom LayoutManager to be used by a JPanel.

However, when I add a Component to the JPanel, the JPanel doesn't call the addLayoutComponent() method of my custom LayoutManager, even though it should:

http://download.oracle.com/javase/tutorial/uiswing/layout/custom.html

(It does call layoutContainer(), as expected)

Hopefully, someone can tell me what I am doing wrong.

How do I get the JPanel to call 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();
        }

        publ开发者_StackOverflowic Dimension preferredLayoutSize(Container parent)
        {
            System.out.println("preferredLayoutSize");
            return new Dimension();
        }

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


How do I get the JPanel to call addLayoutComponent()?

It would only invoke this method if your layout manager uses constraints

panel.add(button);  

Try:

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

This method is intended to be used to pass constraints to the layout manager. I think BorderLayout is the only layout manager that might have used this. However it generally should not be used anymore. Instead LayoutManager2 uses:

public void addLayoutComponent(Component component, Object constraint)

which allows you to pass any Object as a constraint.

0

精彩评论

暂无评论...
验证码 换一张
取 消