It's a good practice to call File methods(like read a text file) within JFrame class or what should I do if not? Thanks for reply.
This is my code:
private void filechooserButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
UPDATE : I edited my code to use SwingWorker, so I hope it's better than was:
private class textFileReader extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt", "text"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
resultTextArea.setText(null);
filePathTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
try (BufferedReader buffReader = new BufferedReader(new FileReader(new File(fileChooser.getSelectedFile().getAbsolutePath())))) {
String line;
while ((line = buffReader.readLine()) != null) {
resultTextArea.append(line + "\n");
}
} catch (Exception exc) {
JOptionPane.showMessageDialog(MainGUI.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
}