17

Hi all! I'm trying to solve an -apparently- simple problem, but I cannot fix it. I'm working on a sample application with Java/Swing libraries; I have a JFrame and a JPanel. I just want to achieve the following objectives:

  1. JPanel MUST be centered inside the JFrame.

  2. JPanel MUST have ALWAYS the size that is specified with
    setPreferredSize() method. It MUST NOT be resized under this size.

I tried by using a GridBagLayout: it's the ONLY way I can do it.

See the sample below:

/* file StackSample01.java */

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

public class StackSample01 {
    public static void main(String [] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.RED);  

        frame.setLayout(new GridBagLayout());
        frame.add(panel, new GridBagConstraints());
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

Here a screenshot:

I would not use a GridBagLayout to do a thing too simple. I tried a simplest solution, by using a Box, but this does not work:

Sample code:

/* file StackSample02.java */

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

public class StackSample02 {
    public static void main(String [] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(100, 100));
        panel.setBackground(Color.RED); // for debug 

        panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect

        Box box = new Box(BoxLayout.Y_AXIS);

        box.add(Box.createVerticalGlue());
        box.add(panel);     
        box.add(Box.createVerticalGlue()); // causes a deformation

        frame.add(box);
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

Here a screenshot,

Any ideas? Thanks to all :-)

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
IT.
  • 311
  • 1
  • 5
  • 24
  • Have you tried using the BorderFactory class to put a border around "panel"? I'm not too familiar with it, otherwise I'd give a more concrete example. – Tony Aug 28 '11 at 20:07
  • 1
    *"I would not use a GridBagLayout to do a thing too simple."* Why not? I have a deep and abiding dislike of GBL, but for this situation, it would be the first layout I'd try. – Andrew Thompson Aug 29 '11 at 08:11
  • @Andrew - full ack, except using GBL, would never use it :-) Instead go for one of the big-three Form, Mig, Design, whatever is the personal favourite. – kleopatra Aug 29 '11 at 08:31
  • @kleopatra you down voted answers for using setXxxSize(), would you be so nice to provide us a proper answer or a link to a proper answer? I am tired of reading your "-1 for this, -1 for that" comments. – mostruash Apr 22 '13 at 11:44
  • @mostruash hint: there's a "frequent" tab .. To be honest, I'm tired of developers who don't do much to find the answer to their questions, or the reasons for a vote to answers (up as much as down, doesn't really make a difference) - after all, finding stuff is the _essence_ of their job. – kleopatra Apr 22 '13 at 12:07

6 Answers6

16

BoxLayout can pretty to hold your setXxxSize(), then just add panel.setMaximumSize(new Dimension(100, 100));

and your output would be

Removed by setMinimumSize(notice if Container has greater size as ... )

enter image description here enter image description here enter image description here

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

public class CustomComponent12 extends JFrame {

    private static final long serialVersionUID = 1L;

    public CustomComponent12() {
        Box box = new Box(BoxLayout.Y_AXIS);
        box.setAlignmentX(JComponent.CENTER_ALIGNMENT);
        box.add(Box.createVerticalGlue());
        box.add(new CustomComponents12());
        box.add(Box.createVerticalGlue());
        add(box);
        pack();
        setTitle("Custom Component Test / BoxLayout");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setMaximumSize(getMinimumSize());
        setMinimumSize(getMinimumSize());
        setPreferredSize(getPreferredSize());
        setLocation(150, 150);
        setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                CustomComponent12 main = new CustomComponent12();
            }
        };
        javax.swing.SwingUtilities.invokeLater(r);
    }
}

class CustomComponents12 extends JPanel {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getMaximumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • @kleopatra somebody can reads between my own lines :-) , my curiosity (and we talking only about deepest JComponents without any childs) how is, or if is possible resurns setXxxSize that another way – mKorbel Aug 29 '11 at 08:54
6

First of all, thanks to all.

I reply another time to my own question, to show everyone the choice I have made. See the sample code below; As you can see, I have included only minimal steps which are absolutely necessary to achieve the goal.

/* file StackResponse.java */

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

public class StackResponse {
    public static void main(String [] args) {

        JPanel panel = new JPanel();
        Dimension expectedDimension = new Dimension(100, 100);

        panel.setPreferredSize(expectedDimension);
        panel.setMaximumSize(expectedDimension);
        panel.setMinimumSize(expectedDimension);

        panel.setBackground(Color.RED); // for debug only

        Box box = new Box(BoxLayout.Y_AXIS);

        box.add(Box.createVerticalGlue());
        box.add(panel);     
        box.add(Box.createVerticalGlue());

        JFrame frame = new JFrame();
        frame.add(box);
        frame.setSize(new Dimension(200, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setMinimumSize(frame.getMinimumSize());   // cannot be resized-

        frame.setVisible(true);

    }
}

Here you can see a screenshot.

Problem solved. Many thanks again to all.

IT

IT.
  • 311
  • 1
  • 5
  • 24
2

create a panel by name "FixedPanel" with GridBagLayout and set preferred size to frame size then add your frame into FixedPanel.

Frame = new JFrame("CenterFrame");         
Frame.setLocation(0, 0);
Frame.setSize(new Dimension(400,400));//dim

JPanel FixedPanel = new JPanel(new GridBagLayout());
FixedPanel.setPreferredSize(Frame.getSize());

JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(100,100));
myPanel.setBackground(Color.BLACK);

FixedPanel.add(myPanel);
Frame.add(FixedPanel);
Frame.setVisible(true);  
Ehsan Jelodar
  • 1,544
  • 19
  • 25
-1

You can do this. I had to make a chess game, and I wanted the chess piece piece to always go in the center of a cell which was a JlayeredPane:

private void formMouseReleased(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    if (jl != null)
    {
        jl.setLocation(evt.getX()+10, evt.getY()+10);
        Component com = findComponentAt(evt.getPoint());
        if (com instanceof JPanel)
        {
            // System.out.println("Yes, it's a jpanel");
            ((JPanel)com).add(jl);
            ((JPanel)com).validate();
        }
    }
}
sabadow
  • 5,095
  • 3
  • 34
  • 51
andrew
  • 1
-3

Its Just Having

jPanel.setBounds(x, y, 1046, 503);

Where x is space for right side and y is space for left side. you have to calculate the space from both side according to screen height and width

Shivling
  • 9
  • 4
-5

use

panel.setMaximumSize(new Dimension(200,200));
panel.setResizable(false)

instead?

confucius
  • 13,127
  • 10
  • 47
  • 66
  • JPanel does not have setResizable(boolean resizable) method. – IT. Aug 28 '11 at 20:35
  • 1
    -1 for setXXSize and inventing api - you know that there's no _obligation_ to answer if you dont know it? Wild guessing _definitely is the wrong-thing-to-do. – kleopatra Aug 29 '11 at 08:00