views:

269

answers:

2

I have created customized Button. For that i have overrided paintComponenet method. How can I set Button Text on such button? I tried doing it using drawString method. But which x,y values should i give? (g.drawString("button text",x,y)). Please till me if anyone has handled this.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    DefaultButtonModel bmodel = (DefaultButtonModel) super.getModel();

    Image im = (new ImageIcon("image")).getImage();
    System.out.println("im is "+im.getSource());
    System.out.println("widthis" + im.getWidth(this));
    int imageX = (getWidth() - im.getWidth(this)) /2;
    int imageY = (getHeight() - im.getHeight(this)) / 2;
    if(!super.isEnabled()) {
        System.out.println("in disabled");
        g.drawImage(disabled, imageX, imageY, this);
       g.drawString( super.getText(), super.getX(),(int) (super.getY() / (1.9)));
    }
    else {
        if(bmodel.isPressed()) {
           System.out.println("in pressed");
            g.drawImage(down, imageX, imageY, this); 
        } else if(bmodel.isRollover()) {
            System.out.println("in roll overed");
            g.drawImage(highlight, imageX, imageY, this);
        } else if(bmodel.isEnabled()) {
            System.out.println("in enabled");
            g.drawImage(normal, imageX, imageY, this);
        } else {
            System.out.println("in else");
            g.drawImage(normal, imageX, imageY, this);
        }
        g.drawString( super.getText(), super.getX(),(int) (super.getY() / (2.5)));
    }



}
+1  A: 

Why don't you just call super(g) on the first line of paintComponent method and use the setText method to change the string on the button.

Something like this:

protected void paintComponent(Graphics g)
{
   super.paintComponent(g);
   // do your customized painting here...
}
Pablo Santa Cruz
super(g) is giving me error.."call to super must be first statement of the constructor"
Nilesh
sorry, it should have been super.paintComponent(g);
Pablo Santa Cruz
That's the ticket - to paint background reverse and do custom painting first.
Pool
A: 

What are you trying to do, you never stated the actual requirement? It looks like you are trying to draw text on top of the image. If so, then there is no need for custom painting, just use:

button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);

You can set rollover and pressed icons as needed.

camickr