views:

139

answers:

4

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?

+2  A: 

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);
camickr
+1  A: 

Are you trying to overlay text on top of image or just position text outside of the image? Positiioning text outside the image is easy and is default behavior as @camickr has mentioned. To move text to top, you may :

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

Also, note that only .gif, .jpg, and .png. will be handled by ImageIcon

ring bearer
+2  A: 

By default, swing buttons have a horizontal text position of SwingConstants.TRAILING, which will draw the text after the icon (think of a checkbox or radio button). If you want the text centered over the icon, you just need to set the button's horizontal text position:

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

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
        }
    }
}
Bragboy