开发者

How does one know what are the valid commands in Swing's getActionCommand()?

How to know which commands are available? I tried looking up in the Java SDK, but didn't find a thing about it.

The only way I can think of is this way

class ButtonListener implements ActionListener {
  ButtonListener() {
  }

  public void actionPerformed(ActionEvent e) {
      System.out.println(e.getActionCommand());
  }
}

but I guess those values must be hardcoded in some part of the framework. Where can I find them?

Thanks

EDIT

Take as example the following code taken from here:

public void actionPerf开发者_如何学Goormed(ActionEvent e) {
    if ("disable".equals(e.getActionCommand())) {
        ...
    }

    ...
 }

The site's author knew there was an action command that was "disable". Where did he get that information from?


You may be thinking of the Action interface, named instances of which are used to establish default key bindings in various L&Fs. The article Key Bindings includes a convenient utility to examine them.

Addendum: As a concrete example, the JButton in ClickCount takes its name and action command from the nested ClickHandler because the hideActionText property of Action is false by default. As another example, Key Bindings shows that buttons have a named action for "pressed" and "released" that is created by createButtonListener() in BasicButtonUI. BasicButtonListener in turn uses a nested UIAction to handle the two commands, as shown here.


You do it by using setActionCommand()

JButton jb = new JButton("MyButton");
jb.setActionCommand("MyButtonCommand");

EDIT:

The site's author got "disable" from this line of code

b1.setActionCommand("disable");


It's whatever you set.

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Button.html#setActionCommand%28java.lang.String%29

My guess is the default is the name of the button.

Your edit:

It could have come from two places.

  1. It was the name of the button (new JButton("disable")), which by default is the action command.
  2. It was the command given by setActionCommand("disable")

It is very important to illustrate that by design it doesn't matter what the source was. We don't care if it's a button, drop down, menu, or anything. All that matters is the "disable" command was given. It's the command pattern. :-)


There are no 'valid' commands. The command is intended for use by your application and has no effect on how the button is handled by Swing.

In the second code example you posted it is being setin the code at the following line

b1.setActionCommand("disable");

For buttons the default is to use the text of the button, if the action command is not set

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜