gpt4 book ai didi

java - 如何使用自定义组件修复 GridBagConstraints anchor ?

转载 作者:行者123 更新时间:2023-12-01 15:01:24 26 4
gpt4 key购买 nike

我制作了一个自定义组件,以便可以显示图像等,但它拒绝正确使用 anchor 并在顶部居中。有人有解决办法吗?另外,如果有人能给我指出一个更简单的布局,我可能会切换,但我已经使用了大量的 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 anchor 位置,您需要设置 X 轴的权重:

gbc.weightx = 1.0;

关于java - 如何使用自定义组件修复 GridBagConstraints anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com