Align text and icon differently in JLabel
Asked Answered
B

2

5

i'm trying to create a JLabel that has text aligned left and icon aligned right, i tried this code:

_ip = new JLabel(ip);
_ip.setFont(boldFont);
_ip.setBounds(5, 0, 100, 50);
_ip.setIcon(images.ipBan);
_ip.setBorder(BorderFactory.createLineBorder(Color.black, 1));
_ip.setHorizontalTextPosition(SwingConstants.LEFT);
add(_ip);

And this is what i get:

Alignment preview

The red image shows the actual image alignment, the gray one shows where i want my image to be.

If i add

_ip.setAlignmentX(JLabel.RIGHT_ALIGNMENT);

Nothing happens, and if i add

_ip.setHorizontalAlignment(JLabel.RIGHT);

Icon is aligned right, but also text is aligned right, and i want it to align left

Is there a way to do it?

Buckram answered 31/3, 2013 at 15:50 Comment(4)
Won't adding a few spaces solves the problem?I mean jLabel.setText("99.222.22.230 (FEW SPACES) ")Tillford
No, this will be a fetched-from-db IPs list, if i choose to add some spaces it means i should know every IP i'm loading, but in fact i don't as they are loaded from a db, so i can't just add spacesBuckram
I know it's a ugly way but your ip string+ " (SPACE)" will do the job.Tillford
There must be a way (tricky or not) to do that, spaces are just a workaround that i don't want to use, mainly because the font i'm using is not monospaced, so if i put some labels into a JList, every icon will be misaligned to othersBuckram
P
7

Alternatively, you can use a JPanel with a suitable layout, as shown here.

image

Painful answered 31/3, 2013 at 17:28 Comment(2)
That was wondeful EG +1, I was about to post an EG on sum length of the string stuff lolTillford
You are welcome! @joeyrohan: Might be possible with TextLayout in a custom LabelUI, for example.Painful
F
6

please DYM???

enter image description here

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

public class CenteredJLabel {

    private JFrame frame = new JFrame("Test");
    private JPanel panel = new JPanel();
    private JLabel label = new JLabel("CenteredJLabel");
    private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");

    public CenteredJLabel() {
        panel.setLayout(new GridBagLayout());
        panel.add(label);
        label.setHorizontalAlignment(SwingConstants.LEFT);
        label.setVerticalAlignment(SwingConstants.CENTER);
        label.setIcon(errorIcon);
        label.setIconTextGap(20);
        label.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                CenteredJLabel centeredJLabel = new CenteredJLabel();
            }
        });
    }
}

EDIT

enter image description here

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

public class CenteredJLabel {

    private JFrame frame = new JFrame("Test");
    private JPanel panel = new JPanel();
    private JLabel labelOne = new JLabel("CenteredJLabel");
    private JLabel labelTwo = new JLabel("1.1.1.1");
    private JLabel labelThree = new JLabel("192.168.255.255");
    private JLabel labelFour = new JLabel("192.168.255.255");
    private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
    private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
    private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
    private Icon questnIcon = UIManager.getIcon("OptionPane.questionIcon");
    private JPanel panelTwo = new JPanel();

    public CenteredJLabel() {
        panel.setLayout(new GridLayout(4, 0, 10, 10));

        labelOne.setHorizontalAlignment(SwingConstants.LEFT);
        labelOne.setVerticalAlignment(SwingConstants.CENTER);
        labelOne.setIcon(errorIcon);
        labelOne.setIconTextGap(20);
        labelOne.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        panel.add(labelOne);

        labelTwo.setHorizontalAlignment(SwingConstants.LEFT);
        labelTwo.setVerticalAlignment(SwingConstants.CENTER);
        labelTwo.setIcon(infoIcon);
        labelTwo.setIconTextGap(20);
        labelTwo.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        panel.add(labelTwo);

        labelThree.setHorizontalAlignment(SwingConstants.LEFT);
        labelThree.setVerticalAlignment(SwingConstants.CENTER);
        labelThree.setIcon(warnIcon);
        labelThree.setIconTextGap(20);
        labelThree.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        panel.add(labelThree);

        panelTwo.setLayout(new BorderLayout());
        panelTwo.setOpaque(false);
        panelTwo.add(labelFour, BorderLayout.WEST);
        panelTwo.add(new JLabel(questnIcon), BorderLayout.EAST);
        panel.add(panelTwo);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenteredJLabel centeredJLabel = new CenteredJLabel();
            }
        });
    }
}
Fabricant answered 31/3, 2013 at 15:59 Comment(13)
Doesn't work. If you remove the frame.pack() instruction and simply do frame.setSize(500,300), it will just center the label, that is not what i want to doBuckram
@Harlandraka I don't think he is trying to show the frame on the center, but see the spacing between the icon and text.Tillford
@joeyrohan I'm not saying he's showing the frame on the center, i'm saying that this solution simply centers the text and the icon on the JLabel, but this is not what i need, so this is not a solution to my problem, and also spacing between text and icon isn't a solution, because i don't know how many chars my text will containBuckram
@Harlandraka But you always know the max : xxx.xxx.xxx.xxx .What exactly you want?May be Label.setIconTextGap() helps?Tillford
@joeyrohan Using the icon text gap is the same as using spaces, if i use i.e. _ip.setIconTextGap(15), then a label with text 151.33.58.1 will have the text and icon aligment that i want, but if my text is 1.1.1.1 it will not align correctly.Buckram
@Harlandraka it all depends on the size of you label.SOk here's a trick (i don't know a simple way) set the icon gap as per the length of your string ..should I try?Tillford
@Harlandraka the above example is perfect it will align correctly.Try for inputs.+1 for the answer.Tillford
@joeyrohan really? Check my first comment, just size manually the frame and you'll see that this is not what i need. Then try to change the text length, and you will see that the icon position will be based on the text lengthBuckram
@Harlandraka then you have to add LayoutManager(Box or BorderLayout) to JLabel and put there a JLabel with text and another JLabel with Icon, see my edit hereFabricant
@Fabricant the problem is still the same, the "i" icon is not aligned with all other iconsBuckram
@Harlandraka please do you understand how I layed JPanel with two JLabels, then in all cases text starting on left side and Icon is sticked on right side, about basic layout ....Fabricant
for active JComponent to put Icon to the undecorated JButtonFabricant
Yes i understand, but it's not what i want, trashgod answer is what i'm looking for.Buckram

© 2022 - 2024 — McMap. All rights reserved.