Java Swing Panel Size - java

Hi I have been learning Java Swing for creating a chess game to practice my Java programming skills.
I've added a JPanel to the east of the JFrame with BorderLayout and I've used the setPrefferedSize(new Dimension(x,y)) method to set the width and height.
After that I have created 4 JPanel and added them with BoxLayout on the previously created panel.
I have tried to set the size of the 4 panels with the setSize(x,y) and setPreferredSize(new Dimension(x,y)) but it dosent work the 4 panels automaticly changed there size to fit the main JPanel and after adding a JLabel on one of them the size of it increased automaticly .
This is my code:
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel a = new JPanel();
a.setPreferredSize(new Dimension(50, 50)); //this dosent work
a.add(min);
a.setBackground(Color.red);
this.add;
JPanel b = new JPanel();
b.setBackground(Color.blue);
this.add(b);
JPanel c = new JPanel();
this.add(c);
JPanel d = new JPanel();
d.setBackground(Color.black);
this.add(d);
How can I change the size of each of these panels?

BoxLayout is best for laying out components with varying sizes along a single axis. From the Javadocs:
"BoxLayout attempts to arrange components at their preferred widths (for horizontal layout) or heights (for vertical layout)."
The idea is that they may have different heights (for a horizontal layout) and it will take the maximum height. And, they definitely may have different widths. Also, BoxLayout works with some, er, "interesting" filler pieces like Box.createHorizontalGlue(). These are actually quite useful for flexible, resizeable layouts once you get the hang of it. But, all in all, BoxLayout is for flexible, resizable layout of items with differing sizes.
For simpler cases, especially if you want both preferred width and preferred height to be "respected", use GridLayout as everybody else has suggested.

Related

Setting component sizes inside Jpanels with Borderlayout

I have a project to copy the google sign-in GUI here . So far I'm still searching on what I'm gonna start with, but after some research I think it is possible on BorderLayout to do this. Im getting how it works by readjusting everything through borders, and I kind of like it because it is quite responsive compared to having null layout and coding every setBounds for each component.
I've been imagining using a background panel, a panel for the fill up form,
and creating panels for each pair of label and textfields to properly create the space and stacking (or nesting) them on top of the other. Our teacher just told us to snip out the image, she just wants if we know how to design something out of scratch. That and also saving the input into a text file.
However, I can't seem to grasp the concept of increasing the component size inside the borders to imitate the gaps between the text fields, like some sort of a padding between components? Using setSize doesnt work and so far my search only results into resizing borders, or perhaps I still have not entered the right searachable term for it?
Also, Ive been looking for another way and I think this project will also work using GridBaglayout. However many people say GridBagLayout is too complicated. What do you think would be easier?
In my experience almost every (99%) of the panels using GridBagLayout can be designed by using all other layouts. So, someone could say that GridBagLayout is optional
In your situation, avoiding the use of a GridBagLayout is easy. Take a look at the following code:
public class NoGridBagLayout extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NoGridBagLayout().setVisible(true));
}
public NoGridBagLayout() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.setBorder(new TitledBorder("borderPanel - BorderLayout"));
JLabel label = new JLabel("Create a google account.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(label.getFont().deriveFont(25f));
borderPanel.add(label, BorderLayout.PAGE_START);
setContentPane(borderPanel);
JPanel gridPanel = new JPanel(new GridLayout(1, 2));
gridPanel.setBorder(new TitledBorder("gridPanel - GridLayout"));
getContentPane().add(gridPanel, BorderLayout.CENTER);
JPanel leftBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
leftBoxedPanel.setLayout(new BoxLayout(leftBoxedPanel, BoxLayout.Y_AXIS));
leftBoxedPanel.setBorder(new TitledBorder("leftBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(leftBoxedPanel);
JPanel rightBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
rightBoxedPanel.setLayout(new BoxLayout(rightBoxedPanel, BoxLayout.Y_AXIS));
rightBoxedPanel.setBorder(new TitledBorder("rightBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(rightBoxedPanel);
}
}
Preview:

BoxLayout ignores subpanel alignment

I have a JPanel with a BoxLayout manager that contains subpanels. I want the components inside these subpanels to have a left alignment, but they always appear centered.
It looks like BoxLayout correctly aligns components that are inserted directly, but fails to do that when they are inside a subpanel.
I have modified the example found in http://www.java2s.com/Tutorial/Java/0240__Swing/YAxisAlignment.htm so each button is placed inside a subpanel, and then the subpanel is placed inside the main panel with the BoxLayout manager:
public class YAxisAlignX {
private static Container makeIt(String title, float alignment) {
String labels[] = { "--", "----", "--------", "------------" };
JPanel container = new JPanel();
container.setBorder(BorderFactory.createTitledBorder(title));
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
// modified loop. the original version does not create JPanel pan.
// adds the buttons directly the the JPanel container with the
// BoxLayout
for (int i = 0, n = labels.length; i < n; i++) {
JPanel pan = new JPanel();
JButton button = new JButton(labels[i]);
pan.add(button);
button.setAlignmentX(alignment);
pan.setAlignmentX(alignment);
container.add(pan);
}
return container;
}
public static void main(String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel1 = makeIt("Left", Component.LEFT_ALIGNMENT);
Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
Container panel3 = makeIt("Right", Component.RIGHT_ALIGNMENT);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
If you execute this version, you can see that the buttons are all centered, despite the alignment set. Why is this happening? Is there any solution? In my case, every subpanel contains several components, and I do not want to add then directly to the main panel.
Thank you very much.
But they are aligned!
First of all, setAlignmentX changes a property at a JComponent level, the layout in which these components are placed may or may not use this information. For example, BoxLayout uses it but FlowLayout and BorderLayout don't.
In your case you are placing some panels with a vertical BoxLayout and you are aligning them in various ways, and it works! It just so happens that the the panels stretch themselves to fit the whole column so actually aligning doesn't change their appearance. You can see this by setting a Border around the panels:
pan.setBorder(BorderFactory.createLineBorder(Color.red));
See:
The fact that the panels contain a button or anything else is mostly irrelevant (it only influences the size that the panel wants to take, and not definitely), the BoxLayout is aligning panels not what is there inside the panels, that's the work of each panel's layout. That's why the buttons wouldn't have its alignment affected by the BoxLayout.
Now how are those buttons deciding its alignment? Well that's up to the layout they are in. The buttons are inside the pan panel that is using the default LayoutManager FlowLayout. Now, as I said, FlowLayout doesn't care for the alignmentX/Y property so the line:
button.setAlignmentX(alignment);
Doesn't accomplish anything. To align in a FlowLayout you need to change its alignment field through FlowLayout.setAligment(int) (docs), you can also do this in the constructor, so If we change the pan declaration to:
JPanel pan = new JPanel(new FlowLayout(FlowLayout.LEFT));
You'll also have the buttons aligned to the left inside their panels:
Of course, all the columns are aligned to the left since the parameter float alignment of makeIt does not influence the FlowLayout's alignment just the BoxLayout's one (and it doesn't matter). You might want to change that argument to an int and call the function with the different FlowLayout constants.
All in all, in the original version the line button.setAlignmentX(alignment); made sense because the buttons were added directly to the container panel and the BoxLayout aligned them properly:
However once you put the buttons inside other panels, the BoxLayout starts aligning the panels (which because of how panels works inside a BoxLayout they were being stretched to fill the whole width) not the buttons, and the buttons alignment is up to the panels layout. That's how it has to work so we can make consistent nested layouts.
I hope that's clear.

How to reduce the space between the 3 swing checkboxes?

I want to reduce the size between the components with in the Formatting group (left side on the image). How to do this?
JPanel formattingGroup = createGroupWithName("Formatting");
formattingGroup.setMinimumSize(new Dimension(250, 20));
formattingGroup.setLayout(new GridLayout(5, 0));
add(formattingGroup);
final JCheckBox showSurface = new JCheckBox("Show surface");
showSurface.setSelected(true);
formattingGroup.add(showSurface);
final JCheckBox showTerrain = new JCheckBox("Show terrain");
showTerrain.setSelected(true);
formattingGroup.add(showTerrain);
final JCheckBox showVehicleStatus = new JCheckBox("Show vehicle status");
showVehicleStatus.setSelected(true);
formattingGroup.add(showVehicleStatus);
JPanel pnl = createGroupWithName("Depth Stretch");
formattingGroup.add(pnl);
JSlider slider = new JSlider(0, 10);
pnl.add(slider);
When using a GridLayout all components are made the same size.
You are adding a JPanel with a TitledBorder and a JSlider to the grid. Therefore the checkboxes will take the same vertical height as that panel.
You need to use a different layout manager for the panel. Maybe a vertical BoxLayout.
You might look at available size variants, discussed in Resizing a Component.
Use gridbaglayout because that gives you the opportunity to give weights, to columns or rows and set spacing and padding values.
I made a Swing application that contains out of 12 Frames and they all are made with GridBagLayout.
I also tried other before that but they all had limits. That's where the GridBagLayout kicks in. It's a bit harder in begin to understand how it works, but once you get feeling with it, it really is best thing to get the components where you want.
If you want i'll give you a cool example of a frame created with GridBagLayout.

Best Swing Layout for 2-dimensional grid of buttons?

I'm trying to create a JDialog like the Symbol dialog in Microsoft Word that you get by choosing Symbol... from the Insert menu. Basically, it's an n x m (n and m are not known until runtime) grid of small buttons. I've got a first version of this working nicely using a GridLayout. The problem is that when you resize the dialog (and there is a requirement that you should be able to resize it), the size of the buttons changes. I need the size of the buttons to remain constant.
But I want the dimensions of the grid containing the buttons to change. For example, if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
I've thought of a couple of ways to fix this:
When the dialog is resized, create a new GridLayout and repopulate it with the buttons. I'm going to try this and see how it looks, but it seems like a clumsy way of doing it.
Use some other type of layout such as a FlowLayout. I took a stab at this, but it put all n x m buttons in one row. I do not want to use horizontal scroll-bars and the buttons ran off the right edge. Anyway, it's supposed to be a 2-dimensional grid of buttons.
What is the best way to solve this layout problem?
Create a buttons panel with GridLayout and set a fixed size (could be calculated at runtime of course) to it. The buttons panel should be contained in a panel of BoxLayout.
Check out the BoxLayout Tutorial
Very Very basic example:
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
JPanel containerPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2));
buttonPanel.add(new JButton("1"));
buttonPanel.add(new JButton("2"));
buttonPanel.add(new JButton("3"));
buttonPanel.add(new JButton("4"));
buttonPanel.setPreferredSize(new Dimension(300, 400));
containerPanel.add(buttonPanel);
frame.getContentPane().add(containerPanel);
frame.pack();
frame.setVisible(true);
}
if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases.
Wrap Layout might be what you are looking for.
I had a similar issue with a single column of buttons, and found that MiGLayout (third-party, available here) was simple and effective for this. It helped both with making a grid and with setting button sizes, although it took me a day or two to get used to its syntax.
But the key is really setting button sizes; GridLayout certainly seems like the way to go for a layout that is, well, a grid. I haven't tested, but I suspect that the built-in setXSize() methods would work just as well. The GridBagLayout tutorial has examples of some things you can do with sizing/positioning.
FlowLayout would be the way to go but you might have some configuration problems. What layout manager does the parent component use?

How to make JLabels start on the next line

JPanel pMeasure = new JPanel();
....
JLabel economy = new JLabel("Economy");
JLabel regularity = new JLabel("Regularity");
pMeasure.add(economy);
pMeasure.add(regularity);
...
When I run the code above I get this output:
Economy Regularity
How can I get this output, where each JLabel starts on a new line? Thanks
Economy
Regularity
You'll want to play around with layout managers to control the positioning and sizing of the controls in your JPanel. Layout managers are responsible for placing controls, determining where they go, how big they are, how much space is between them, what happens when you resize the window, etc.
There are oodles of different layout managers each of which allows you to layout controls in different ways. The default layout manager is FlowLayout, which as you've seen simply places components next to each other left to right. That's the simplest. Some other common layout managers are:
GridLayout - arranges components in a rectangular grid with equal-size rows and columns
BorderLayout - has one main component in the center and up to four surrounding components above, below, to the left, and to the right.
GridBagLayout - the Big Bertha of all the built-in layout managers, it is the most flexible but also the most complicated to use.
You could, for example, use a BoxLayout to layout the labels.
BoxLayout either stacks its components on top of each other or places them in a row — your choice. You might think of it as a version of FlowLayout, but with greater functionality. Here is a picture of an application that demonstrates using BoxLayout to display a centered column of components:
An example of code using BoxLayout would be:
JPanel pMeasure = new JPanel();
....
JLabel economy = new JLabel("Economy");
JLabel regularity = new JLabel("Regularity");
pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS));
pMeasure.add(economy);
pMeasure.add(regularity);
...
I read this piece of code:
pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.VERTICAL));
It seems BoxLayout doesn't have VERTICAL. Upon searching, this will work using the following code:
pMeasure.setLayout(new BoxLayout(pMeasure, BoxLayout.Y_AXIS));
Here is what you need to use:
JLabel economy = new JLabel("<html>Economy<br>Regularity</html>");
A quick way is to use html within the JLabel.
For instance include the <br/> tag.
Otherwise, implement a BoxLayout.
Make a separate JPanel for each line, and set the dimensions to fit each word:
JLabel wordlabel = new JLabel("Word");
JPanel word1 = new JPanel();
word1.setPreferredSize(new Dimension(#,#);
This should work for each word. You can then add each of those JPanels to your main JPanel. This also allows you to add other components next to each word.

Categories

Resources