Can I put text on top of an image with a button?

I have .jpg images in my buttons. I would also like to add text on top of the images. To do this, I use the following syntax:

JButton btn = new JButton(label,icon);

But I do not see the text in the buttons (image only). What am I doing wrong?

+3
source share
5 answers

I have no idea why you do not see the text and the icon. By default, the text should be applied to the right of the icon.

To display text on top of the icon you are using:

JButton button = new JButton(...);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);
+15
source

, swing, paint(). , , .

package test;

import java.awt.Graphics;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonTest {
    public static void main(String[] args){
        new ButtonTest().test();
    }

    public void test(){
        JFrame frame = new JFrame("Biohazard");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pnl = new JPanel();
        pnl.add(new MyButton());
        frame.add(pnl);
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    class MyButton extends JButton{
        public void paint(Graphics g){
            //anything you want
        }
    }
}
+3

JButton button = new JButton(text,icon); button.setVerticalTextPosition(SwingConstants.TOP); button.setHorizontalTextPosition(SwingConstants.CENTER);

.

+3

? , @camickr. , :

ImageIcon icon = new ImageIcon(pathToicon);
JButton myButton = new JButton("Press me!", icon);
myButton.setVerticalTextPosition(SwingContstants.TOP);

, .gif,.jpg .png. ImageIcon

+2

SwingConstants.TRAILING, ( ). , , :

JButton button = new JButton(label, icon);
button.setHorizontalTextPosition(SwingConstants.CENTER);
+2

Source: https://habr.com/ru/post/1742817/


All Articles