我制作了一个自定义组件,因此我可以显示图像等,但它拒绝正确使用锚点并居中于顶部。有人有修复吗?此外,如果有人能指出我可以切换的更简单的布局,但我已经使用了很多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));
}
}
答案 0 :(得分:1)
要使定位适用于GridBagConstraints.NORTHWEST
锚位置,您需要在X轴上设置权重:
gbc.weightx = 1.0;