我有一个具有这种布局的面板:



有一个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;


现在,我要使图标(或JLabel)相对于标签(或图标)居中,如下所示:



我该如何实现?我不想将图标放入JLabel中,因为我需要将其放入自己的JLabel中(因为我想稍后更改图标)。

最佳答案

你能试一下吗

lastConstraints.anchor = GridBagConstraints.CENTER;

09-05 13:48