How to right-justify icon in a JLabel?

假如想象 提交于 2019-11-27 09:29:01

Is this the desired effect?

Addendum: I think a panel is the way to go.

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

public class TestJLabelIcon {

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

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setLayout(new GridLayout(0, 1));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(createPanel("abc"));
                frame.add(createPanel("defghij"));
                frame.add(createPanel("klmn"));
                frame.add(createPanel("opq"));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

            private JPanel createPanel(String s) {
                JPanel p = new JPanel(new BorderLayout());
                p.add(new JLabel(s, JLabel.LEFT), BorderLayout.WEST);
                Icon icon = UIManager.getIcon("FileChooser.detailsViewIcon");
                p.add(new JLabel(icon, JLabel.RIGHT), BorderLayout.EAST);
                p.setBorder(BorderFactory.createLineBorder(Color.blue));
                return p;
            }
        });
    }
}

You should use:

label1.setHorizontalTextPosition(SwingConstants.LEFT);

(Set the position of the text, relative to the icon)

Fred Andrews

I found a much easier way to do this. I needed to have this kind of layout in a JTable, and did the right justification by getting the text width and then manually setting the width between the text and the icon. I subclassed a DefaultTableCellRenderer for my JTable

public class FixedWidthRenderer extends DefaultTableCellRenderer 
{
    ...
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, 
        boolean isSelected, boolean hasFocus, int row, int column)
    {
        ...
        FontMetrics met = super.getFontMetrics(super.getFont());
        int width = met.stringWidth(super.getText());                
        super.setIconTextGap(DESIREDWIDTH - width); 
        ...
    }
}

Works great!
And yes, for real code one should check that the text width is not bigger than the DESIREDWIDTH.


For automatic right-alignment without a fixed width that works with columns of variable width:

    @Override
    public void setBounds(int x, int y, int width, int height) {
        super.setBounds(x, y, width, height);
        if (getIcon() != null) {
            int textWidth = getFontMetrics(getFont()).stringWidth(getText());
            Insets insets = getInsets();
            int iconTextGap = width - textWidth - getIcon().getIconWidth() - insets.left - insets.right - PADDING;
            setIconTextGap(iconTextGap);
        } else {
            setIconTextGap(0);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!