How to override setText for custom JButton
Hi
From the Swings Hack book, I have the code for a custom JButton.
I would like to setText for this button so that the text is set over the image on the button.
Would someone know how I can do this?
import java.awt.*;
import javax.swing.*;
publicclass ImageButtonextends JButton{
public ImageButton(String img){
this(new ImageIcon(img));
}
public ImageButton(ImageIcon icon){
setIcon(icon);
setMargin(new Insets(0,0,0,0));
setIconTextGap(0);
setBorderPainted(false);
setBorder(null);
setText(null);
setSize(icon.getImage().getWidth(null),
icon.getImage().getHeight(null));
}
}
Thanks!
[1374 byte] By [
fdgfda] at [2007-11-27 10:21:57]

# 1
Something like this should do it...
import java.awt.*;
import javax.swing.*;
public class ImageButton extends JButton {
private static final long serialVersionUID = 1;
public ImageButton(ImageIcon icon, String text) {
setIcon(icon);
setMargin(new Insets(0, 0, 0, 0));
setIconTextGap(0);
setBorderPainted(false);
setBorder(null);
setText(text);
setSize(icon.getImage().getWidth(null), icon.getImage().getHeight(null));
}
}
Or just add a public setText() method accepting a String...
# 2
> so that the text is set over the image on the button
Not exactly sure what you mean by over, but playing around with these two properties should give you what you want:
setHorizontalTextPosition(JButton.CENTER);
setVerticalTextPosition(JButton.CENTER);
# 3
Thanks, I've not tested the setText("test") yet, but when I call setText on the new ImageButton object, the text gets set on the underlying JButton and actually displays the JButton to the right of the Image object.
So I basically see my nice Image button with a part of a JButton sticking out to the right side with the text on it. I obviously need the text to sit on top of the Image.
fdgfda at 2007-7-28 17:13:04 >

# 4
I gave you the answer above.
If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
see http://homepage1.nifty.com/algafield/sscce.html,
that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
Don't forget to use the "Code Formatting Tags",
see http://forum.java.sun.com/help.jspa?sec=formatting,
so the posted code retains its original formatting.