1

似乎一切都向中心挤压,但我不知道为什么。这是我的代码。我尽量让它易于阅读。

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;

/**
 *
 * @author rubixibuc
 */
public class RulesWindow extends JFrame {

    public GridBagLayout layout = new GridBagLayout();
    public GridBagConstraints constr = new GridBagConstraints();
    public DefaultComboBoxModel modelE = new DefaultComboBoxModel();
    public DefaultComboBoxModel modelA = new DefaultComboBoxModel();
    public DefaultListModel modelL = new DefaultListModel();

    public RulesWindow()
    {
        super("Rules Window");
        /* layout for window
        |_P_|__E__|_T_|__A__|_a_|
        |                   |xxx|
        |                   |xxx|
        |                   |xxx|
        |_________L_________|_M_|
         X = no fill
         P = pattern field
         E = extension combobox
         T = target action
         A = action combobox
         a = add rule
         M = remove rule
         L = rule list
        */

        setLayout(layout);

        JTextField P = new JTextField(); // 0,0,1,1 
        JComboBox E = new JComboBox(modelE); // 1,0,2,1
        JTextField T = new JTextField(); // 3,0,1,1
        JComboBox A = new JComboBox(modelA); // 4,0,2,1
        JButton a = new JButton("+"); // 6,0,1,1
        JList L = new JList(modelL); // 1,1,6,4
        JButton M = new JButton("-"); // 6,4,1,1

        changeConstraints(0,0,1,1);
        add(P);
        changeConstraints(1,0,2,1);
        add(E);
        changeConstraints(3,0,1,1);
        add(T);
        changeConstraints(4,0,2,1);
        add(A);
        changeConstraints(6,0,1,1);
        add(a);
        changeConstraints(1,1,6,4);
        add(L);
        changeConstraints(6,4,1,1);
        add(M);

        setSize(200,200);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    public final void changeConstraints(int gridx, int gridy, int gridwidth, int gridheight)
    {
        constr.anchor = GridBagConstraints.NORTHEAST;
        constr.fill = GridBagConstraints.BOTH;
        constr.gridx = gridx;
        constr.gridy = gridy;
        constr.gridwidth = gridwidth;
        constr.gridheight = gridheight;
    }
    @Override
    public final Component add(Component comp)
    {
        layout.setConstraints(comp, constr);
        super.add(comp);
        return comp;
    }
}

提前致谢。我在评论中绘制了它应该是什么样子的图表。

我调用重写方法的方式也是正确的吗?

4

1 回答 1

2

每当我在这里

似乎一切都向中心挤压,但我不知道为什么

与 GridBagLayout 相关,我问 weightx 和 weighty 约束在哪里?

所以一个可能的快速解决方案:记住将 GridBagConstraints weightx 和 weighty 字段设置为合理的值(您可以将其默认为 1.0 以开始然后使用它们)。

于 2012-04-21T19:38:03.123 回答