在"North"边框布局中左右对齐两个 JLabel



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

这是我的代码:

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

所以我需要左边的topTxtLabel和右边的logoutTxtLabel。我试图再次实现Border Layout,使用"WEST"one_answers"EAST",但没有成功。想法?

假设您的应用程序由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);
    }
}

最新更新