views:

413

answers:

2

Hi,

I am trying to override default java Button behavior and trying to add additional label to a button. I am new to java GUI and thought that overriding paint method will solve my problem, but when I do that and draw additional label in Button paint method it looks fine, but my label disappears if I click on that button in my application.

I tried to find some tutorials on how to override java.awt.Component, but couldn't find anything. Thanks.

A: 

Here is a page describing how painting works in awt that might help. However, if all you are after is to add an extra label to the button, you should consider changing subclassing to composition. It's much safer. Your composite class can extend Component and define it's own paint-method.

class MyButton extends Component {
    private Button button;
    private Label label;

    public MyButton(String label, String buttonLabel) {
        label = new Label(label);
        button = new Button(buttonLabel);
    }

    public paint(Graphics g) {
        label.paint(g);
        button.paint(g);
    }

    ...
}
crunchdog
A: 

You can't really override 'paint' in the basic AWT controls and still have them work right, because in Button, for instance, much of the painting behavior is done by the peer classes (a WButton in Windows, for instance). I wrote many of the AWT controls for the OS/2 JVM way back in 1.1.x, and I can't imagine this working the way you want it to unless things have changed dramatically with the AWT (unlikely).

If you want to really control painting in situations like this, you need to either roll your own or go with a Swing button and then explore the "UI component" (the delegate object responsible for painting the control among other things - part of the "look and feel" being used at the time).

Basically, the AWT controls are 'native' - i.e. there's a real Windows button there and some java code wrapped around it. The Swing controls are 'pure java'; but delegate much of their behavior and almost all of their appearance to the UI controllers in the look-and-feel packages.

M1EK
well, then you will be surprised, because it works fine for me =)
negative
I meant, it won't work the way you want to in all situations. In the original poster's case, for instance, what's likely happening is that the native control is painting itself in response to the mouse button down event in Windows - and completely ignoring anything happening on the java side in the process.
M1EK