6

i have 2 Java classes:

public abstract class IconNames {
/**
 *
 */
public static final String ButtonFett = java.util.ResourceBundle.getBundle("recources/buttonproperties").getString("fett");
}

and

public class EditorPanelActionListener implements ActionListener{
.
.
.
String buttonText = e.getActionCommand();
switch(buttonText)
    {
        case IconNames.ButtonFett: //Error: constant string expression required
            replace(XmlTags.BOLD);
            break;
    }
 .
 .
 .
 }

The EditorPanelActionListener fire the error "constant string expression required", whats the problem?

Thanks!

rainer zufall
  • 100
  • 2
  • 7
  • 8
    Short answer: The cases of a `switch` statement must be compile time constants. Your variable can only be evaluated at runtime. – jlordo Sep 05 '13 at 09:35
  • can e.getActionCommand() return enum instead of a String? – rajesh Sep 05 '13 at 09:37

1 Answers1

2

You should not mix up program logic and user interface texts. The action command is a property distinct from the text shown and only defaults to the shown text if not set explicitly.

public abstract class IconNames {
  public static final String ButtonFett_CMD = "DO-BOLD";
  public static final String ButtonFett_TXT = java.util.ResourceBundle.getBundle("recources/buttonproperties").getString("fett");
}

JButton b=new JButton(IconNames.ButtonFett_TXT);
b.setActionCommand(IconNames.ButtonFett_CMD);

String buttonText = e.getActionCommand();
switch(buttonText)
{
    case IconNames.ButtonFett_CMD: // user language independent
        replace(XmlTags.BOLD);
        break;
}

This works for subclasses of AbstractButton which includes menu items as well. If you are dealing with Action implementations directly (which I doubt seeing your switch statement) you should differentiate between the Action.NAME and Action.ACTION_COMMAND_KEY property.

Holger
  • 285,553
  • 42
  • 434
  • 765