Java GridBadLayout定位

时间:2018-02-20 00:06:03

标签: java swing layout-manager gridbaglayout

如果对我的问题有任何帮助/建议,我将不胜感激。我附上了我的简单程序的图像,显​​示组件的位置似乎有点偏。我的问题是 - 为什么ComboBox From...以及TextField Enter value here...从左角开始到目前为止?我已经给出了gridx=0因此它将组件定位在窗口的最边缘,但是组件从边缘开始一些像素。我该如何解决? 另外,我需要做什么/考虑去除彼此之间的依赖关系?我的意思是如何在一行中将组件定位在我想要的任何位置而不影响另一行中其他组件的位置。谢谢! 一段代码:

    JPanel container = new JPanel();
    container.setLayout(new GridBagLayout());
    getContentPane().add(container, BorderLayout.NORTH);
    TitledBorder outputCenter;
    GridBagConstraints c = new GridBagConstraints();

    label = new JLabel("Choose measure system to convert");
    label.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 2; 
    c.insets = new Insets(10, 0, 20, 0);
    container.add(label, c);

    fromList = new JComboBox<String>(convertFrom); 
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth =1; 
    c.ipadx = 20; 
    c.anchor = GridBagConstraints.LINE_START; 
    container.add(fromList, c);

    toList = new JComboBox<String>(convertTo);
    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 1;
    c.ipadx = 20;
    container.add(toList, c);

    //Field where user enters the value to be converted
    input = new JTextField("Enter value here...");
    input.setPreferredSize(new Dimension(150,30));;
    input.setEditable(true);
    input.setBackground(Color.WHITE);
    input.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    input.addMouseListener(new MouseAdapter(){
        public void mouseClicked(MouseEvent e){
            input.setText("");}});
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1; 
    c.ipady = 20;
    container.add(input, c);

    //The area where the output/result is shown
    output = new JTextArea(10,30);
    output.setEditable(false);
    output.setFont(new Font("Serif", Font.BOLD, 12));
    output.setBackground(Color.WHITE);
    outputCenter = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "Output");
    outputCenter.setTitleJustification(TitledBorder.CENTER);
    output.setBorder(outputCenter);
    c.gridx = 1;
    c.gridy = 2;
    c.insets = new Insets(50,5,10,10);
    c.gridwidth = 3;
    container.add(output, c);

    //Convert button
    convert = new JButton("Convert");
    c.gridx = 0;
    c.gridy = 3;
    c.ipadx = 50; 
    container.add(convert, c);
}

输出:Output

1 个答案:

答案 0 :(得分:1)

请记住,GridBagLayout是一个“灵活的网格”布局管理器。它仍然依赖于行和列的概念,但每个行和列都有自己的大小,基于组件的要求和应用它们的约束。

这意味着,由于c.anchor = GridBagConstraints.LINE_START和共享同一列的JTextField的空间要求的组合,您的组合框已与左侧位置对齐。

您“可以”将c.anchor = GridBagConstraints.LINE_START更改为c.anchor = GridBagConstraints.LINE_END,而将(在您的情况下)将组合框与列的右边缘对齐,例如......

Possible solution

另一种解决方案是使用容器组合来降低布局的整体复杂性。例如,您可以将组合框添加到它们自己的容器中,以隔离的方式管理它们的布局要求,然后在大型方案中布置该容器