Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.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 如何修复GridBagConstraint';s锚定自定义组件?_Java_Swing_Custom Component_Gridbaglayout - Fatal编程技术网

Java 如何修复GridBagConstraint';s锚定自定义组件?

Java 如何修复GridBagConstraint';s锚定自定义组件?,java,swing,custom-component,gridbaglayout,Java,Swing,Custom Component,Gridbaglayout,我制作了一个自定义组件,以便显示图像等,但它拒绝正确使用锚点和顶部的中心。有人有办法吗?另外,如果有人能告诉我一个更简单的布局,我可能会切换,但我已经使用了很多GridBag,所以这将很难 一般测试的测试等级: package com.launcher.test; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.aw

我制作了一个自定义组件,以便显示图像等,但它拒绝正确使用锚点和顶部的中心。有人有办法吗?另外,如果有人能告诉我一个更简单的布局,我可能会切换,但我已经使用了很多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));
}
}

要获得定位以适用于
GridBagConstraints.NORTHWEST
锚定位置,您需要设置X轴上的权重:

gbc.weightx = 1.0;

非常感谢你!我想不出来,但现在效果很好!