【问题标题】:Java vertical layout hugging left edgeJava垂直布局拥抱左边缘
【发布时间】:2015-05-23 06:30:55
【问题描述】:

我在 Java 中的布局有一些问题,下图代表了我想要完成的任务。目前我正在使用;

Box vBox = Box.createVerticalBox();

垂直分隔项目,但它们倾向于在中心分组而不是 拥抱左边缘。实现这一目标的最佳方法是什么?

编辑:设置对齐方式;

JComboBox combo  = new JComboBox<Integer>(numPlayers);
combo.setMaximumSize(new Dimension(100, 30));
combo.setAlignmentX(JComponent.RIGHT_ALIGNMENT );
vBox.add(combo);

似乎没有正确对齐组件,而是将组件左边缘与面板的中心线对齐。

【问题讨论】:

    标签: java layout alignment


    【解决方案1】:

    您可以使用垂直框。现在您需要设置添加到框中的组件的对齐方式:

    component.setAlignmentX( JComponent.LEFT_ALIGNMENT );
    box.add( component );
    ...
    

    编辑:

    您可以使用 GridBagLayout。当空间增加时,组件将保持在首选大小。但是,如果您将框架缩小得太小,组件将恢复为 (0, 0),这是您的最小尺寸。如果您不喜欢这种行为,那么您需要为所有组件设置最小尺寸:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    
    public class SSCCE extends JPanel
    {
        public SSCCE()
        {
            setLayout( new BorderLayout() );
            JComponent component;
    
            JPanel vBox = new JPanel( new GridBagLayout() );
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = GridBagConstraints.REMAINDER;
    
            component = new JTextField(10);
            gbc.anchor = GridBagConstraints.LINE_START;
            vBox.add(component, gbc);
    
            component = new JTextField(10);
            gbc.anchor = GridBagConstraints.LINE_END;
            vBox.add(component, gbc);
    
            component = new JTextField(30);
            gbc.anchor = GridBagConstraints.CENTER;
            vBox.add(component, gbc);
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new SSCCE() );
            frame.setLocationByPlatform( true );
            frame.pack();
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });
        }
    }
    

    【讨论】:

    • @BenJacob、This doesn't seem to work,,然后发布一个 SSCCE 来演示问题,而不是图片。另一种方法见编辑。
    猜你喜欢
    • 2012-02-15
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多