Add JComponents in the middle of the JPanel - java

I would like to have a trade-off between FlowLayout and GridBagLayout. In a nutshell, I've some components to add in my JPanel (I don't know how many of these, it's a creation at runtime) and I would like that these components to be center vertically.
FlowLayout was ideal for my goal, but it adds components at the top of JPanel. So, I decided to use GridBagConstraints, as someone suggested here (Java layout manager vertical center) but my problem with this solution is that GridBagLayout doesn't create a new line automatically, so I've just one row (vertically center, at least!!!) where my components are inserted that goes beyond the screen size. Could anyone give me some tricks about that???

I would like that these components to be center vertically. FlowLayout was ideal for my goal, but it adds components at the top of JPanel
You are never forced to use a single panel or layout manager. You can use nested panels. For example:
JPanel centered = new JPanel( choose your layout manager );
Box vertical = Box.createVerticalBox();
vertical.add( Box.createVerticalGlue() );
vertical.add( centered );
vertical.add( Box.createVerticalGlue() );
frame.add( vertical );
The glue in the vertical panel will take up equal amounts of extra space which leaves the "centered" panel vertically centered. So you can add components to the centered panel using whatever layout you want.

Related

Make buttons unresizable

So I was trying to google how to set a default size to JButtons so that they don't grow as the JFrame is resized. I didn't see a setDefaultSize method but the closest one I could find that does a similar job is setMaximumSize(). However, it doesn't seem to work in my situation and I'm guessing it's because I'm using Grid Layout for positioning my buttons in the frame, here's a small piece of my code:
rightPanel.add(ButtonA);
rightPanel.add(ButtonB);
rightPanel.add(ButtonC);
outerPanel.add(leftPanel);
outerPanel.add(rightPanel);
getContentPane().add(outerPanel);
Here's a picture of what happens:
I would also like to have my buttons in the middle of the right panel when I'm resizing (just like they are now but a lot smaller). Any idea of how I can fix this? I'm assuming that I have to use another layout or something.
Thanks
EDIT: I modified my code to use BoxLayout but it does not seem to put the buttons in the middle. The X Alignment is working but Y Alignment is not doing anything:
ButtonA.setAlignmentX(CENTER_ALIGNMENT);
ButtonA.setAlignmentY(CENTER_ALIGNMENT);
ButtonB.setAlignmentX(CENTER_ALIGNMENT);
ButtonB.setAlignmentY(CENTER_ALIGNMENT);
ButtonC.setAlignmentX(CENTER_ALIGNMENT);
ButtonC.setAlignmentY(CENTER_ALIGNMENT);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
rightPanel.add(ButtonA);
rightPanel.add(ButtonB);
rightPanel.add(ButtonC);
outerPanel.add(leftPanel);
outerPanel.add(rightPanel);
getContentPane().add(outerPanel);
EDIT2: Fixed with vertical glue.
A GridLayout will always resize the components to fill the space available.
Try using a vertical BoxLayoutinstead. See the section from the Swing tutorial on How to Use Box Layout for more information and examples.
Encapsulate each JButton in a JPanel with a FlowLayout, and then add those FlowLayout JPanels to the rightPanel instead of the JButtons themselves. This will allow you to keep your evenly spaced buttons, but won't make them expand to take up the entire space that the parent container has available.
If you don't want them evenly spaced, but to be three consecutive buttons one after another top down, you can make the right panel have a BorderLayout, add a sub panel to the north area of the BorderLayout with the original GridLayout that the right panel had, and then add those FlowLayout panels containing the JButtons.

Laying out components cardlayout

So I'm just creating a simple game screen and I want to lay out my two buttons like this:
I was advised to use CardLayout (I've not worked with layouts before) so I read up on the java docs and created this:
canvas.setLayout(new CardLayout());
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
//buttons
final JButton btn1 = new JButton(play);
btn1.setBorder(BorderFactory.createEmptyBorder());
btn1.setContentAreaFilled(false);
final JButton btn2 = new JButton(instructions);
btn2.setBorder(BorderFactory.createEmptyBorder());
btn2.setContentAreaFilled(false);
card1.add(btn1);
card2.add(btn2);
canvas.add(card1);
canvas.add(card2);
However, it produces this:
I can't seem to find any information about positioning with card layout. My guess is that I shouldn't be using this layout at all, so what layout should I use?
Card layout is used to show only one of multiple components in the layout. You can select programmatically which card to show and the rest will be hidden from view.
If you add two buttons in card layout, you can see only one. You shouldn't be using it for your specific situation. you can use Box layout with X axis
The BoxLayout manager is constructed with an axis parameter that
specifies the type of layout that will be done. There are four
choices:
X_AXIS - Components are laid out horizontally from left to right.
Y_AXIS - Components are laid out vertically from top to bottom.
LINE_AXIS - Components are laid out the way words are laid out in a
line, based on the container's ComponentOrientation property. If the
container's ComponentOrientation is horizontal then components are
laid out horizontally, otherwise they are laid out vertically. For
horizontal orientations, if the container's ComponentOrientation is
left to right then components are laid out left to right, otherwise
they are laid out right to left. For vertical orientations components
are always laid out from top to bottom.
PAGE_AXIS - Components are
laid out the way text lines are laid out on a page, based on the
container's ComponentOrientation property. If the container's
ComponentOrientation is horizontal then components are laid out
vertically, otherwise they are laid out horizontally. For horizontal
orientations, if the container's ComponentOrientation is left to right
then components are laid out left to right, otherwise they are laid
out right to left. For vertical orientations components are always
laid out from top to bottom.

how to reposition JButton on resizing the window

I have kept a JButton in the bottom middle part of my JFrame. Now whenever I resize the window the JButton should be repositioned (in the new centre) depending on new resized window. Can anyone tell me how to accomplish this. Thanks in advance.
Components in Swing are rendered according to the frame's layout manager. The default layout manager is BorderLayout, which divides the frame into five logical parts: North (up), South (down), East (right), West (left) and Center (everything in between). Components are centered by default.
You can create subframes for each part, and give them the a similar layout manager, or a completely different layout manager. in your case you'd want to create a new subframe at the South position of the main frame, and put your button in one of its North, Center or South positions.
Hope this helps...
1) Create a JPanel usign a FlowLayout with "center alignment" and add your JButton to the panel.
2) Add this panel to the "SOUTH" of the content pane which uses a BorderLayout by default.
i would take a look at LayoutManagers
BorderLayout would do the trick
http://java.sun.com/docs/books/tutorial/uiswing/layout/border.html

Scrollable flow panel

I need to create a panel where I can put some rectangles and it automatically reorder just inserting a scrollbar and growing up vertically. Also this panel can be resizable and again the rectangles must to be reordered to correctly be displayed inside the panel.
If I understand the question you want components to wrap to the next line so that the panel grows vertically while the width remains fixed.
If so then check out the WrapLayout
Note: the FlowLayout already supports the wrapping of components to a new row on the panel. This issue is that the preferred size calculation assumes all components are placed on a single row. The WrapLayout overrides the preferred size calculation to support the wrapping of components on a new row.
Use a JScrollPane. If you never want a horizontal scroll bar you can add the following:
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
(By default the scroll pane will add horizontal and vertical scroll bars when required.)
The scroll pane itself will only be resizeable if you add it to a Container with the appropriate layout manager; e.g.
JFrame frm = new JFrame();
frm.setLayout(new BorderLayout());
JScrollPane sp = new JScrollPane();
frm.add(sp, BorderLayout.CENTER); // Adding a component to the CENTER will cause the component to grow as the frame is resized.

Can you set a permanent size for a JPanel inside of a JFrame?

My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look
Image
Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?
I also would like to set the size of those buttons so they are not so huge (BorderLayout is being used for the buttons and TextField)
GridBagLayout is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on the API page for it. Using GridBagLayout, the components won't fill the whole grid space if you don't want them to and can even stay the size that you ask it to be. To keep a component's size from changing, I would set all three available size constraints:
water.setPreferredSize(new Dimension(20, 20));
water.setMinimumSize(new Dimension(20, 20));
water.setMaximumSize(new Dimension(20, 20));
For your buttons, I would definitely use an inner panel as Bryan mentions. You could use either a GridLayout like he suggests or a FlowLayout if you don't want all the buttons to be the same size. Add all your buttons to that inner panel instead of the main one.
If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own JPanel. Set each of those parent JPanel's to have a layout type of GridBagLayout. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout should by default lay each board out in the center of the parent JPanel. So as the window is resized, the JPanel parent area will get larger or smaller, but the checkerboard components inside will remain the same size.
Alternatively, you could have your blue squares scale to the right size as the window is resized by having each checkboard square be a JPanel with a BorderLayout layout manager and adding the JLabel (with a blue background color) to its BorderLayout.CENTER location.
As for your buttons, try something like this:
JPanel theButtonPanel = new JPanel(new BorderLayout());
JButton button1 = new JButton("Fire");
JButton button2 = new JButton("Pass");
JButton button3 = new JButton("Forfiet");
JPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8));
innerButtonContainer.add(button1);
innerButtonContainer.add(button2);
innerButtonContainer.add(button3);
theButtonPanel.add(innterButtonContainer);
Lastly, consider using a design tool for your Swing user interface. Netbeans has an excellent UI designer built into it. Download Netbeans here.
If you can setResizeable( false ) on the top level frame you can then set your layout manager to null and hard code each location and size via setBounds. This is how I would do it (contingent on resizing of course).
I have had success solving problems like these using TableLayout which is a third party layout manager. You will need to download it and read the tutorial but the key would be to set the justification to CENTER when adding the JButtons to their positions in the layout.

Categories