Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JLabel和图标在GridBagLayout中彼此居中_Java_Swing_Constraints_Gridbaglayout - Fatal编程技术网

Java JLabel和图标在GridBagLayout中彼此居中

Java JLabel和图标在GridBagLayout中彼此居中,java,swing,constraints,gridbaglayout,Java,Swing,Constraints,Gridbaglayout,我有一个布局如下的面板: 在图标前面有一个JLabel,它具有以下labelConstraints,并且图标的lastConstraints显示在JLabel之后: GridBagConstraints lastConstraints = new GridBagConstraints(); GridBagConstraints labelConstraints = new GridBagConstraints(); lastConstraints.fill = GridBagCo

我有一个布局如下的面板:

在图标前面有一个JLabel,它具有以下
labelConstraints
,并且图标的
lastConstraints
显示在JLabel之后:

  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;
现在我想让图标(或JLabel)相对于标签(或图标)居中,如下所示:


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

最简单的方法是将图标放在标签上;您可以随时使用
setIcon()
更改图标。或者,使用对齐或对齐。您能试试吗

lastConstraints.anchor = GridBagConstraints.CENTER;

同一行中的两个元素怎么可能有…,禁用插入,