How to right-justify icon in a JLabel?

后端 未结 3 626
醉话见心
醉话见心 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:41

    Is this the desired effect?

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

    image

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

提交回复
热议问题