Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put text on top of a image in a button?

I have .jpg images in my buttons. I also would like to put some text on top of the images. I use the following syntax for that:

JButton btn = new JButton(label,icon);

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

like image 968
Roman Avatar asked Apr 26 '10 12:04

Roman


2 Answers

I have no idea why you are not seeing the text and icon. By default the text should be painted to the right of the icon.

To display the text on top of the icon you use:

JButton button = new JButton(...);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);
like image 98
camickr Avatar answered Oct 09 '22 23:10

camickr


If you want to play any way you like in any swing component, you can very well override the paint() method. This way you can do whatever you like.

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
        }
    }
}
like image 32
bragboy Avatar answered Oct 09 '22 23:10

bragboy