我制作了一个自定义组件,以便我可以显示图像等,但它拒绝正确使用锚点并在顶部居中。有没有人有修复?此外,如果有人能指出我更简单的布局,我可能会切换,但我已经使用了很多 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));
}
}