How to right-justify icon in a JLabel?

后端 未结 3 633
醉话见心
醉话见心 2020-12-02 00:02

For a JLabel with icon, if you setHorizontalTextPosition(SwingConstants.LEADING), the icon is painted right after text, no matter how wide the label is.

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 00:34

    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);
            }
        }
    

提交回复
热议问题