Question

I want to fill a JPanel GridLayout with Many JLabels. However, I want each LabelText to have the same width in pixels. The Labels all have 2 parts:

VarA:       123.4
VarB:       Green
DateMax  12/03/13

I can accomplish this using Monospaced fonts, as I just need to count total characters.

Is there a way to do the same for TrueType fonts?

Was it helpful?

Solution

A small example on how to do this:

public class AdjustedLabel extends JPanel {

    public AdjustedLabel(String leftText, String rightText) {
        JLabel leftLabel = new JLabel(leftText, SwingConstants.LEFT);
        JLabel rightLabel = new JLabel(rightText, SwingConstants.RIGHT);
        setLayout(new BorderLayout());
        add(leftLabel, BorderLayout.WEST);
        add(rightLabel, BorderLayout.EAST);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("label testing");
        JPanel panel = new JPanel(new GridLayout(3, 1));
        panel.add(new AdjustedLabel("VarA:", "123.4"));
        panel.add(new AdjustedLabel("VarB:", "Green"));
        panel.add(new AdjustedLabel("DateMax:", "12/03/13"));
        frame.setContentPane(panel);
        frame.setSize(200, 100);
        frame.setVisible(true);
    }
}

Edit: Some adjustments to make the component more idiomatic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top