Search code examples
javaswingborder-layout

Two column layout and first column truncated


I am trying to create a JPanel using BorderLayout which contains two JLabel. The first JLabel should use all available horizontal space excluding the space of the second JLabel.

At the moment my result looks like this:

enter image description here

What I am trying to accomplish is this:

enter image description here

Here's a SSCCE:

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

public class TwoColumnsTruncate {
    public TwoColumnsTruncate() {
        JPanel panel = new JPanel(new BorderLayout());
        JLabel left = new JLabel("This is a really large label and its text should be truncated with ellipsis");
        JLabel right = new JLabel("Some short text");
        panel.add(left, BorderLayout.WEST);
        panel.add(right, BorderLayout.EAST);
        JFrame frame = new JFrame(getClass().getSimpleName());
        frame.getContentPane().add(panel);
        frame.setMinimumSize(new Dimension(400, 75));
        frame.setMaximumSize(new Dimension(400, 75));
        frame.setVisible(true);
    }

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

Do you have any tips for me to accomplish this?


Solution

  • Somewhat to my surprise, I find that you can accomplish this by assigning the left label to BorderLayout.CENTER instead of BorderLayout.WEST. I'd have to study the docs some more (maybe a lot more) to figure out why that is.