【问题标题】:align left and right two JLabels in a "North" BorderLayout在“North”BorderLayout 中左右对齐两个 JLabel
【发布时间】:2015-02-23 23:14:55
【问题描述】:

我在我的应用程序中使用BorderLayoutsetLayout(new BorderLayout()); 我需要在JPanel"NORTH"中左右对齐两个JLabels

这是我的代码:

JPanel top = new JPanel();
top.add(topTxtLabel);
top.add(logoutTxtLabel);
add(BorderLayout.PAGE_START, top);

所以我需要左侧的 topTxtLabel 和右侧的 logoutTxtLabel。 我尝试再次实现边框布局以使用“WEST”和“EAST”,但没有奏效。想法?

【问题讨论】:

    标签: java alignment jlabel


    【解决方案1】:

    假设您的应用程序由JFrameBorderLayout 组成,您可以尝试以下操作:再次将JPanel 的布局模式设置为BorderLayout。在框架的北部添加面板。然后在东西方添加2个JLabels。您也可以将JFrame 替换为另一个JPanel

    import java.awt.BorderLayout;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    
    public class Main 
    {
    
        public static void main(String[] args) 
        {
            new Main();
        }
    
        Main()
        {
            JFrame frame = new JFrame("MyFrame");
            frame.setLayout(new BorderLayout());
    
            JPanel panel = new JPanel(new BorderLayout());
            JLabel left = new JLabel("LEFT");
            JLabel right = new JLabel("RIGHT");
            JPanel top = new JPanel(new BorderLayout());
    
            top.add(left, BorderLayout.WEST);
            top.add(right, BorderLayout.EAST);
            panel.add(top, BorderLayout.NORTH);
            frame.add(panel, BorderLayout.NORTH);
            frame.add(new JLabel("Another dummy Label"), BorderLayout.SOUTH);
    
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    【讨论】:

    • 正如我所说,我尝试将 BorderLayout WEST 和 EAST 结合在一个主要的 JPanel NORTH 中,但它没有用......还有其他想法吗?? :(
    • 它对我有用(见我的编辑)。这就是我从你的问题中解释的。如果您打算采用不同的行为,请更具体地说明您的需求。
    猜你喜欢
    • 2011-11-25
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多