user2336315
user2336315

Reputation: 16067

Get the name of the variable of the button

I work on a project with git where encoding may be different for several machines.

If I set this :

private JButton translationButton1 = new JButton("←");
translationButton1.addActionListener(this);

Then I set the listener :

@Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }

I know it's possible to get the "←" by using e.getActionCommand() but I'm afraid that if somebody who haven't the same encoding as me (Cp1252 for example), I'm not sure to get "←".

It is possible to get the name of the button in the actionPerformed method (if(???.equals("translationButton1")) ? (I don't want to use an anonymous inner type because I have several actionListener to set)

Thanks

Upvotes: 1

Views: 851

Answers (3)

Martin Dvoracek
Martin Dvoracek

Reputation: 1738

You can get encoding on user's computer by System.getProperty("file.encoding")

So for you the code should look like:

@Override
    public void actionPerformed(ActionEvent e) {
    String encoding =System.getProperty("file.encoding");
    if (encoding.equals("UTF-8"))
       // do something
    else if (encoding.equals("Cp1252"))
       // do something else
    // else if (encoding.equals("someEncoding"))
       do something else yet
    }

Nevertheless, I would recommend you also the approach, that @whiskeyspider has desribed here...it's cleaner practice for this case..

Upvotes: 1

martinez314
martinez314

Reputation: 12332

No, but you can set an action command:

translationButton1.setActionCommand("translationButton1");

And then check for the command:

public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand.equals("translationButton1") {
        // do something
    }
}

Upvotes: 4

Andrew Thompson
Andrew Thompson

Reputation: 168825

It is possible to get the name of the button..?

1 button might be assigned to 3 different attribute names or none. So no, it is not possible to get 'the' variable name.

Upvotes: 1

Related Questions