Which java swing layout should I use

旧巷老猫 提交于 2019-12-06 07:02:28

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?

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);
}

Forget about the base layouts, especially the GridBagLayout, and give a look at MigLayout, this will save you a lot of troubles.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!