DorianD
DorianD

Reputation: 75

Java Swing Error

I've been given a practical to do, and it comes with a ImageEditor file which I can show if needed however it's lengthy so I've not posted it on here.

I have to implement a save link and have been given the code which I have stored in a separate class file:

public class SaveAction extends AbstractAction{
    public SaveAction(String text, ImageIcon icon, String desc, Integer mnemonic){
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
    }

    public void actionPerformed(ActionEvent e){
       // Just print out a message for now.
       System.out.println("Save");
   }
}

And then creating an instance in the main class:

Action saveAction = new SaveAction(
    "Save", new ImageIcon("img/save.png"), "Save the image", KeyEvent.VK_S);

However it is coming up with the error:

The Constructor SaveAction(String, ImageIcon, String, int) is undefined.

Any help would be greatly appreciated

Upvotes: 3

Views: 103

Answers (3)

pushy
pushy

Reputation: 9635

Your constructor needs an Integer object, not the int primitive. In contrast to the other solutions I would advise you to use Integer.valueOf instead of new Integer, especially as KeyEvent.VK_S will always represent the same int value:

Action saveAction = new SaveAction("Save", new ImageIcon("img/save.png"), "Save the image", Integer.valueOf(KeyEvent.VK_S)));

See here for more details.

Upvotes: 0

Marcelo Tataje
Marcelo Tataje

Reputation: 3881

Action saveAction = new SaveAction("Save", new ImageIcon("img/save.png"), "Save the image",
KeyEvent.VK_S);

Is the form you're calling the method, but, notice that your constructor:

public SaveAction(String text, ImageIcon icon, String desc, Integer mnemonic)

KeyEvent.VK_S returns an int which is a primitive type. Your constructor expects a class Integer which is like an int but, as you can see, it is not a primitive type, it is a class which has methods and attributes. So then you can invoke your constructor as this:

Action saveAction = new SaveAction("Save", new ImageIcon("img/save.png"), "Save the image",
    new Integer(KeyEvent.VK_S)));

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15664

You have the constructor as:

public SaveAction(String text, ImageIcon icon, String desc, Integer mnemonic)

and you are calling :

new SaveAction("Save", new ImageIcon("img/save.png"), "Save the image",KeyEvent.VK_S);

The error is due to this :

KeyEvent.VK_S must be an int and not Integer and you have Integer as the last argument. So try changing it or just cast it as new Integer(KeyEvent.VK_S)

Upvotes: 3

Related Questions