tags:

views:

14

answers:

2

I have a panel with GridLayout(1, 3) but i want centralize the content of cells in this layout(without addition Panels):

public MainMenu() {
        setLayout(new GridLayout(1, 3));

        setBorder(BorderFactory.createLineBorder(Color.BLUE));
        setOpaque(false);


        ImageComponent img = new ImageComponent("resources/music.png", true, this);
        add(img);
        ImageComponent img1 = new ImageComponent("resources/video.png", true, this);
        add(img1);
        ImageComponent img2 = new ImageComponent("resources/audio", true, this);
        add(img2);


    }

Because if i just add this 3 ImageComponents to MainMenu they appears upwards.

A: 

I believe what you're wanting requires you to call setLayoutData on your image components - check the examples here.

Will A
+1  A: 

GridLayout will size all components to fill the available space. So, if the dimensions of your 3 ImageComponents are 50x50, 50x50, and 75x75, they will all be sized to 75x75. From there it is up to ImageComponent how it paints itself.

Most likely ImageComponent implements paintComponent something like this:

protected void paintComponent(Graphics g) {
    g.drawImage(image, 0, 0, this);
}

That will paint the image in the upper-left corner, not centered.

This will paint a centered image:

protected void paintComponent(Graphics g)
{
    super.paintComponent(g);
    int iw = image.getWidth(this);
    int ih = image.getHeight(this);

    if (iw != -1 && ih != -1)
    {
        int w = getWidth();
        int h = getHeight();
        g.drawImage(image, (w -iw)/2, (h-ih)/2, this);
    }
}
Devon_C_Miller
Thanks Devon! You are the best))))
Le_Coeur