简体   繁体   中英

Add multiple jlabel on jpanel and on same line using box layout

Want to add two jlabel with some space on same line to jpanel, japnel layout is set to box layout,due to some constraints i can't change layout to another and property of box layout from Y_AXIS to LINE_AXIS, so please provide me with some solution, so i can put jlabel on same line..

在此处输入图片说明

contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));

So please let me know the solution for the same mentioned above.

Wrap your labels in a JPanel with a Border layout. Add one to the West panel and another to the East panel. Set the alignment of the JLabels as needed. Then add the JPanel to your box layout.

Try this out: JPanel with GridLayout , and JLabel s left and right aligned. The frame is a Box still uses a box. What should interest you is the JPanel panel code. That's where I'm adding the labels. All you have to do is nest components and layouts

import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class TwoLabels extends JFrame{

    public TwoLabels(){
        Box box = Box.createVerticalBox();

        JPanel panel = new JPanel(new GridLayout(1, 2));
        panel.setBorder(new LineBorder(Color.black));

        JLabel label1 = new JLabel("Hello");
        JLabel label2 = new JLabel("World");
        label1.setHorizontalAlignment(JLabel.LEADING);
        label2.setHorizontalAlignment(JLabel.TRAILING);
        panel.add(label1);
        panel.add(label2);

        box.add(new JPanel(){
            public Dimension getPreferredSize(){
                return new Dimension(300, 300);
            }
        });
        box.add(panel);

        add(box);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new TwoLabels();

    }
}

It looks like you believe you can't change the layout because you're dealing with the content pane of a JFrame and you don't want to change the rest of the window.

If that's the case, you can use nested layouts by adding the two JLabels to a separate JPanel (let's call it labelPanel) and adding that to the content pane. It would look something like this:

JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
labelPanel.add(leftLabel);
labelPanel.add(Box.createGlue()); //creates space between the JLabels
labelPanel.add(rightLabel);

contentPane.add(labelPanel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM