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:
JPanel MUST be centered inside the JFrame.
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 :-)
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
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 ... )
use
instead?
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:
create a panel by name "FixedPanel" with GridBagLayout and set preferred size to frame size then add your frame into FixedPanel.
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.
Here you can see a screenshot.
Problem solved. Many thanks again to all.
IT