As a little side project I'd thought it would cool to make a text editor. I'm currently stuck on opening files. This is my code for opening the file(e is an ActionEvent, open is a JMenuItem):
else if (e.getSource() == open) {
JFileChooser choice = new JFileChooser();
int option = choice.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try{
Scanner scan = new Scanner(new FileReader((open).getSelectedFile().getPath()));
}
}
}
The try block is giving me the trouble. Eclipse is saying that getSelectedFile() is undefined for type JMenuItem. It also appears to be undefined for MenuItems as well. Is there another way to approach this, or another method that works the same?
JFileChooser − To create a file chooser. JFileChooser. showOpenDialog() − To show an open file dialog.
JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc .
Commonly used Constructors: Constructs a JFileChooser pointing to the user's default directory. Constructs a JFileChooser using the given File as the path. Constructs a JFileChooser using the given path.
public final class FileNameExtensionFilter extends FileFilter. An implementation of FileFilter that filters using a specified set of extensions. The extension for a file is the portion of the file name after the last ".". Files whose name does not contain a "." have no file name extension.
You need to call getSelectedFile() on the JFileChooser once it has returned, so change your code to:
choice.getSelectedFile()
private void selectfileActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jFileChooser=new JFileChooser();
StringBuffer buffer;
buffer = new StringBuffer();
int result= jFileChooser.showOpenDialog(this);
if(result==JFileChooser.APPROVE_OPTION)
{
try {
FileReader reader;
reader = null;
JOptionPane.showMessageDialog(this,"hii user clicked open sysytem");
File file=jFileChooser.getSelectedFile();
reader=new FileReader(file);
int i=1;
while(i!=-1)
{
i=reader.read();
char ch=(char) i;
buffer.append(ch);
}
notepad.setText(buffer.toString());
} catch (FileNotFoundException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
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