How to set text above and below a JButton icon?

Posted by mre on Stack Overflow See other posts from Stack Overflow or by mre
Published on 2011-11-13T18:32:19Z Indexed on 2011/11/14 1:51 UTC
Read the original article Hit count: 296

Filed under:
|
|

I want to set text above and below a JButton's icon. At the moment, in order to achieve this, I override the layout manager and use three JLabel instances (i.e. 2 for text and 1 for the icon). But this seems like a dirty solution.

Is there a more direct way of doing this?

Note -
I'm not looking for a multi-line solution, I'm looking for a multi-label solution. Although this article refers to it as a multi-line solution, it actually seems to refer to a multi-label solution.


EXAMPLE

import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public final class JButtonDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }


    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(new JMultiLabelButton());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class JMultiLabelButton extends JButton
    {
        private static final long serialVersionUID = 7650993517602360268L;

        public JMultiLabelButton()
        {
            super();
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            add(new JCenterLabel("Top Label"));
            add(new JCenterLabel(UIManager.getIcon("OptionPane.informationIcon"))); 
            add(new JCenterLabel("Bottom Label"));
        }
    }

    private static final class JCenterLabel extends JLabel
    {
        private static final long serialVersionUID = 5502066664726732298L;

        public JCenterLabel(final String s)
        {
            super(s);
            setAlignmentX(Component.CENTER_ALIGNMENT);
        }

        public JCenterLabel(final Icon i)
        {
            super(i);
            setAlignmentX(Component.CENTER_ALIGNMENT);
        }
    }

}

enter image description here

© Stack Overflow or respective owner

Related posts about java

Related posts about swing