Reputation: 1514
Hi, I am new to the Java language. I used Eclipse as my development tool. I have code to open the file dialog box and it did, but I have two problems:
Here is my code:
package PDFAnnotationPackage;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.io.*;
public class MainForm extends JFrame implements ActionListener {
public static void main(String[] args) {
// TODO Auto-generated method stub
new MainForm();
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(300, 300);
setLocation(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(MainForm.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println("Open menu item clicked");
// load from file
}
if (fileChooser.showOpenDialog(this) == JFileChooser.CANCEL_OPTION ) {
}
} else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
}
How can I solve the issues? Thanks in advance.
Upvotes: 0
Views: 1702
Reputation: 686
Your dialog box appear again because you're calling a method showOpenDialog twice. Try this
if (command.equals("Quit")) {
// Close application
} else if (command.equals("Open")) {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(parent);
if (returnVal == FileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
} else if (command.equals("Save")) {
// Save menu item action
}
Upvotes: 1
Reputation: 285401
You're calling fileChooser.showOpenDialog(this)
multiple times and that's why your program is behaving as it's behaving. Instead call fileChooser.showOpenDialog(this)
once, and save its value to a variable.
In fact, you don't even need this empty block:
if (fileChooser.showOpenDialog(this) ==
JFileChooser.CANCEL_OPTION ) {
}
So get rid of it!
Upvotes: 1