Home > Software engineering >  Java : How to place text on top of an Image on top of a Button?
Java : How to place text on top of an Image on top of a Button?

Time:11-11

Adding an image to a JButton works as expected.
Adding Text to a JButton works as expected.
When adding both Text & an Image to a JButton it adds the 2 items side by side as opposed to on top of one another.

Here is sample code.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;

public class ToolBarSample {
  public static void main(final String args[]) {
    JFrame frame = new JFrame("JToolBar Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JToolBar toolbar = new JToolBar();
    toolbar.setRollover(true);

    JButton b2 = new JButton();
    b2.setText("Big Button");
    b2.setIcon(new ImageIcon("C:\\Downloads\\Java.png"));
    b2.setBackground(Color.RED);
    b2.setFocusable(false);
    b2.setOpaque(true);
    Dimension buttonSize = new Dimension(340,27);
    b2.setPreferredSize(buttonSize);
    b2.setMinimumSize(buttonSize);
    b2.setMaximumSize(buttonSize);
    b2.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
    b2.setVerticalAlignment(SwingConstants.CENTER);

    toolbar.add(b2);
    
    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    contentPane.add(pane, BorderLayout.CENTER);
    frame.setSize(550, 350);
    frame.setVisible(true);
  }
}

The above code generates a large red button with an Image and the text "Big Button".

enter image description here

How can I get the Text moved from the right to be on top of the image. The black box shows the location where I would like the Text to be displayed.

enter image description here

How is this done? What changes are required to accomplish this?

CodePudding user response:

To center the text hozitontally/vertically on the Icon you can use:

JButton button = new JButton("Centered");
button.setIcon( ... );
button.setHorizontalTextPosition(JLabel.CENTER);
button.setVerticalTextPosition(JLabel.CENTER);

If you need the text in some other location on top of the Icon then check out: JButton settext specific position

  • Related