问题
I need to create this frame:
Which layout should I use? I am thinking about box or grid layout but then menu on the right will be a problem.
回答1:
There is a lot of repetition in your code. I would break down each section and make it a separate component and focus on it's individual layout needs.
In you main screen you have 4 main areas (excluding the menu).
I would use something like GridBagLayout
to layout these 4 sections. This allows each section the ability to grow to it's required height, without effecting the others. You can also supply individual growth hints to each section as you see fit.
The first section is a JLabel
, so it's pretty simple
This section is basially three labels with slightly different alignments. I would still use a GridBagLayout
as it provides the greatest flexibility to allow for individual cell alignment, while allowing you to provide sizing hints (for example, I might make the time row in width as the screen size is changed).
This section is a little more complicated. Basically, it's the same component on the left and right, with some clever properties, you would be able to change the position of the labels without to much of an issue.
The individual dots/labels could be laid out using a GridLayout
. I might err on the side of caution and use a GridBagLayout
, as it would allow the labels to be different sizes to the dots
I would then use something like a GridLayout
to place each side onto a component (which would then be placed on the main screen)
Again, this simple the same component mirrored. I would simply create a single component that could be adjusted via a property to change the alignment.
I would then simply use a GridBagLayout
to lay out each label as required. I'd do it this way because it allows each row the ability to have it's own height.
I also have 15 years referring experience in Karate. Can I come work for you?
回答2:
If you go with a AWT
layout, GridBagLayout gives you the most control.
I adopted the following function from an example from java2s.com.
/**
* A helper method to add Components to a Container
* using GridBagLayout
*/
private static void addComponent(Container container,
Component component, int gridX, int gridY,
int gridWidth, int gridHeight, int anchor, int fill)
{
Insets insets = new Insets(0, 0, 0, 0);
GridBagConstraints gbc = new GridBagConstraints(
gridX, gridY, gridWidth, gridHeight, 1.0, 1.0,
anchor, fill, insets, 0, 0
);
container.add(component, gbc);
}
回答3:
Forget about the base layouts, especially the GridBagLayout
, and give a look at MigLayout, this will save you a lot of troubles.
来源:https://stackoverflow.com/questions/15422871/which-java-swing-layout-should-i-use