JLabel和图标在GridBagLayout中以彼此为中心。

时间:2022-08-31 11:58:35

I have a panel with this layout:

我有一个面板和这个布局:

JLabel和图标在GridBagLayout中以彼此为中心。

There is a JLabel with the following labelConstraints in front of the icon and the icon has the lastConstraints to display after a JLabel:

在图标前面有一个JLabel和下面的labelConstraints,图标有一个JLabel后显示的lastConstraints:

  GridBagConstraints lastConstraints = new GridBagConstraints();
  GridBagConstraints labelConstraints = new GridBagConstraints();

  lastConstraints.fill = GridBagConstraints.HORIZONTAL;
  lastConstraints.anchor = GridBagConstraints.NORTHWEST;
  lastConstraints.weightx = 1.0;
  lastConstraints.gridwidth = GridBagConstraints.REMAINDER;
  lastConstraints.insets = new Insets(8, 4, 8, 8);

  labelConstraints = (GridBagConstraints) lastConstraints.clone();
  labelConstraints.weightx = 0.0;
  labelConstraints.gridwidth = 1;

Now I want to have the icons (or the JLabel) centered in relation to the label (or the icon), like this:

现在我想让图标(或JLabel)与标签(或图标)相关,像这样:

JLabel和图标在GridBagLayout中以彼此为中心。

How can I achieve this? I don't want to put the icon into the JLabel as I need it to be in it's own JLabel (cause I want to change the icon later).

我怎样才能做到这一点呢?我不想把图标放到JLabel中,因为我需要它在它自己的JLabel中(因为我想在后面更改图标)。

2 个解决方案

#1


2  

can you try

你能试一试

lastConstraints.anchor = GridBagConstraints.CENTER;

#2


1  

The easiest way is to put the icon on the label; you can change the icon at any time using setIcon(). Alternatively, use either BoxLayout alignment or GroupLayout.Alignment.

最简单的方法是把图标放在标签上;您可以在任何时候使用setIcon()更改图标。或者,可以使用BoxLayout对齐或grouplayout .对齐。

#1


2  

can you try

你能试一试

lastConstraints.anchor = GridBagConstraints.CENTER;

#2


1  

The easiest way is to put the icon on the label; you can change the icon at any time using setIcon(). Alternatively, use either BoxLayout alignment or GroupLayout.Alignment.

最简单的方法是把图标放在标签上;您可以在任何时候使用setIcon()更改图标。或者,可以使用BoxLayout对齐或grouplayout .对齐。