I am developing an application.
I am trying to call a method on menu item click, but how to call it I don't know.
My menu code is as follow:
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmLoadImage = new JMenuItem("Load Image");
mnFile.add(mntmLoadImage);
JMenuItem mntmSaveImage = new JMenuItem("Save Image",s.save("/images", ""));
mnFile.add(mntmSaveImage);
JSeparator separator = new JSeparator();
mnFile.add(separator);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenuItem mntmIncreaseBright = new JMenuItem("Increase Bright");
mnEdit.add(mntmIncreaseBright);
JMenuItem mntmDecreaseBright = new JMenuItem("Decrease Bright");
mnEdit.add(mntmDecreaseBright);
JSeparator separator_1 = new JSeparator();
mnEdit.add(separator_1);
JMenuItem mntmRestoreImage = new JMenuItem("Restore Image");
mnEdit.add(mntmRestoreImage);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelpCtrl = new JMenuItem("Help ctrl + K");
mnHelp.add(mntmHelpCtrl);
JMenuItem mntmAboutImageEditor = new JMenuItem("About Image Editor");
mnHelp.add(mntmAboutImageEditor);
JSeparator separator_2 = new JSeparator();
mnHelp.add(separator_2);
JMenuItem mntmAboutCompany = new JMenuItem("About Company");
mnHelp.add(mntmAboutCompany);
My function code is as follow:
public void save(String path, String name) throws IOException {
if (scaled != null) {
name += scaled.getWidth() + "x" + scaled.getHeight();
ImageIO.write(scaled, "png", (ImageOutputStream) new File(path + File.separator + name + ".png"));
} else {
throw new NullPointerException("Scaled instance is null");
}
}
I am calling function in save image menu item but its shows an error. here s is object of class in which I have define method save.
mntmSaveImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// get the path and the name
save(path, name);
}
});
Maybe a JFileChooser will be useful to get the path and the name, here is a little sample :)
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
path = chooser.getSelectedFile().getAbsolutePath();
name = chooser.getSelectedFile().getName();
}
If I don't say some mistake, parent is your Container such as a JFrame.
Hope it helps !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With