Question

I'm trying to create a sub-class of the JButton component that will enable or disable itself based on a condition (which looks like below)

public interface Condition {
    public static final Condition TRUE  = new Condition() { 
                                          public boolean test() {
                                              return true;
                                          } };
    public static final Condition FALSE = new Condition() { 
                                          public boolean test() {
                                              return false;
                                          } };
    public boolean test();
}

However, the JButton code is all based on the actual boolean value stored privately in the JButton class. My question is: which method of JButton can be overridden to update its stored isEnabled boolean (via setEnabled(boolean))? Would it be update(Graphics)? or repaint()? OR some other function?

Edit: Realized that what I'm trying to create is actually impossible, unless you have a separate thread that waits short periods of time and forces the button to check its status (which is gross and I don't want to do that). The fact is, buttons are reactive only. It would be possible to accomplish this with some overhead by whoever uses the button class, but at that point it'd be easier to just write listeners on whatever is actually changing and toggle the button at that point. Woops.

Was it helpful?

Solution

The DefaultButtonModel, for example, maintains a stateMask, which includes a bit for the enabled state. You could implement the ButtonModel interface accordingly.

Addendum: As an alternative, and as noted in the article Key Bindings, "Another advantage of Actions is that they have an enabled state which provides an easy way to disable the action without having to track which component it is attached to." See How to Use Actions for more.

OTHER TIPS

I strongly suggest using Actions to implement such a feature.

You should enable/disable action attached to your button. In Swing same action can be associated with many types of components such as buttons, menu items etc. By disabling a specific action you will automatically disable all associated components.

This becomes very convenient when you have toolbars, context menus etc with the same set of actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top