Search code examples
javaimageswingjlabelimageicon

Getting label icon to appear above text


I am trying to get the JLabel icon to appear above the text for the label.

Currently I have the following code;

URL loc = null;
        ImageIcon img = null;
        JLabel label = null;

        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        loc = Test.class.getResource("/Images/imageName.jpg");
        img = new ImageIcon(loc);
        label = new JLabel("someText", img, JLabel.CENTER);
        label.setIconTextGap(0);
        label.setVerticalTextPosition(JLabel.BOTTOM);
        label.setHorizontalTextPosition(JLabel.RIGHT);
        frame.getContentPane().add(label);

The output I currently see is the label text to the right of the image icon. Can anyone suggest what to change?


Solution

  • label.setVerticalTextPosition(JLabel.BOTTOM);
    label.setHorizontalTextPosition(JLabel.CENTER);
    

    You need to center align on the horizontal axis for the text to appear under the icon.