【问题标题】:How to fix GridBagConstraint's anchor with custom component?如何使用自定义组件修复 GridBagConstraints 锚点?
【发布时间】:2023-03-15 02:00:01
【问题描述】:

我制作了一个自定义组件,以便我可以显示图像等,但它拒绝正确使用锚点并在顶部居中。有没有人有修复?另外,如果有人能指点我一个更简单的布局,我可能会切换,但我已经使用了很多 GridBag 所以很难。

一般测试的测试类:

package com.launcher.test;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.launcher.swing.ModViewer;

public class Test extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;

public GridBagConstraints gbc = new GridBagConstraints();

public static void main(String[] args) {
    new Test();
}

public Test() {
    super("Super Installer");
    JPanel j = new JPanel(new GridBagLayout());
    addObjs(j);
    this.add(j);
    this.setSize(500, 500);
    this.setVisible(true);
}

public void addObjs(JPanel j) {
    setGBC(0, 0);
    gbc.weighty = 1.0;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.gridwidth = 2;
    gbc.gridheight = 2;
    gbc.ipadx = 50;
    j.add(new ModViewer(), gbc);
    setGBC(2, 0);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHEAST;
    j.add(new JButton("Add Mod"));
}

private void setGBC(int i, int j) {
    gbc.gridx = i;
    gbc.gridy = j;
}

@Override
public void actionPerformed(ActionEvent e) {
}

}

ModViewer 类,本质上是一个盒子:

package com.launcher.swing;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import com.launcher.Main;

@SuppressWarnings("serial")
public class ModViewer extends JPanel {

public ModViewer() {
    setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.black),
            BorderFactory.createEmptyBorder(0, 0, 250, 250)));
    setPreferredSize(new Dimension(250, 250));
}
}

【问题讨论】:

    标签: java swing custom-component gridbaglayout


    【解决方案1】:

    要使定位适用于GridBagConstraints.NORTHWEST 锚位置,您需要在 X 轴上设置权重:

    gbc.weightx = 1.0;
    

    【讨论】:

    • 非常感谢!我想不通,但现在效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2021-08-09
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多