How to align JButton text to the left of the icon?

0

I need to align the text of JButton to the left of the icon as I do?

I tried using the

 button.setHorizontalAlignment(SwingConstants.LEFT);

But this method does not align the text the way I want it.

It's getting the same as the first but I want the second to be equal:

Hereisagenericcodeforcreatingthebutton:

publicvoidgenericMethod(){JFrameframe=newJFrame("JFrame Example");
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        JButton button = new JButton();
        button.setText("GenericButton");
        button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/nextnext.png")));
        button.setHorizontalAlignment(SwingConstants.RIGHT);
        panel.add(button);
        frame.add(panel);
        frame.setSize(300, 300);

        frame.setVisible(true);
    }
    public static void main(String s[]) {
     new NewClass().genericMethod();

    }

The return of the above code is:

    
asked by anonymous 21.02.2018 / 19:33

1 answer

3

Try the following:

jButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);          
jButton.setHorizontalAlignment(SwingConstants.RIGHT);                
jButton.setHorizontalTextPosition(SwingConstants.LEFT);

Source: Changing Icon Position On Jbutton

I made tests here and it took just the line below to make the arrow to the right of the text. Do the test yourself by replacing the path of the two buttons of the code below and pointing to your icon:

import java.awt.FlowLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class JButtonAlinhaTextIconTest {

    public void genericMethod() {

        JFrame frame = new JFrame("JFrame Example");
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        JButton button1 = new JButton();
        JButton button2 = new JButton();

        button1.setText("button1");
        button2.setText("button2");

        try {
            button1.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/res/arrow-right-black.png"))));
            button2.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/res/arrow-right-black.png"))));
        } catch (IOException e) {
            e.printStackTrace();
        }


        button1.setHorizontalTextPosition(SwingConstants.LEFT);
        panel.add(button1);
        panel.add(button2);
        frame.add(panel);
        frame.setSize(300, 300);

        frame.setVisible(true);
    }

    public static void main(String s[]) {

        SwingUtilities.invokeLater(() -> new JButtonAlinhaTextIconTest().genericMethod());
    }
}

Only button1 was applied to the configuration and only it aligned the left icon. See the result I got:

    
21.02.2018 / 20:19