Luis de la Cal
Luis de la Cal

Reputation: 41

Increase gap between icon and button java

I am doing a program in java in which you have to select a category with a button.

I'm trying to put an icon and text in the JButton, but I can't quite get the alignment right. I want a wider space to the left between the left side of the button and the icon.

I have read that you can create an invisible line border to solve this, but my JButton already has a border.

choose_Animals = new JButton ("ANIMALS");
    choose_Animals.setIcon(categoriesIcon[0]);
    choose_Animals.setHorizontalAlignment(SwingConstants.LEFT);
    choose_Animals.setIconTextGap(20);
    choose_Animals.setOpaque(false);
    choose_Animals.setContentAreaFilled(false);
    choose_Animals.setForeground(Color.BLACK);
    choose_Animals.setBorder(border);
    choose_Animals.setFocusable(false);
    choose_Animals.setFont(p);
    choose_Animals.setBounds(90, 220,470, 85);
    choose_Animals.addActionListener(this);
    this.add(choose_Animals);

Upvotes: 1

Views: 1091

Answers (1)

camickr
camickr

Reputation: 324207

Do you know if what I ask for is possible with a null layout?

Positioning the text/icon of a button has nothing to do with a layout manager. These are properties of the component itself.

And yes, you should be using a layout manager, not a null layout. The time to learn using layout managers is now, not some time in the future.

I have read that you can create an invisible line border to solve this,

You can use an EmptyBorder to give addition space to one of the 4 inset positions.

but my JButton already has a border.

You can use a CompoundBorder to combing your current Border with the EmptyBorder

Read the section from the Swing tutorial on How to use Borders for more information and examples.

Upvotes: 1

Related Questions