You can implement a basic message dialog via the JOptionPane.showMessageDialog() method. The first parameter to showMessageDialog() is a component to position the dialog relative to and the second parameter is usually a string to display in the dialog.
try {
in = new Scanner(new File("data.txt"));
} catch(Exception ex) {
JOptionPane.showMessageDialog(this,"Could not open data.txt.");
System.exit(1);
}
To ask the user a simple question with a yes or no answer, use the method JOptionPane.showConfirmDialog().
int response = JOptionPane.showConfirmDialog(this, "Are you sure you want to quit?"); if(response == JOptionPane.YES_OPTION) System.exit(0);
To ask the user to provide a single, simple item of text input, use the method JOptionPane.showInputDialog(). If the user enters a response and clicks OK, showInputDialog will return the string they entered. If the user cancels the dialog, showInputDialog returns null.
String response = JOptionPane.showInputDialog(this, "Enter a number to search for."); if(response != null) search(response);
Instead of hard-coding file names into your application, you may want to give your user the option to select files to open. The JFileChooser class offers methods to display a standard file open dialog and return a File object representing the file the user has selected.
JFileChooser chooser = new JFileChooser();
int response = chooser.showOpenDialog(this);
if(response == JFileChooser.APPROVE_OPTION) {
File theFile = chooser.getSelectedFile();
try {
in = new Scanner(theFile);
}
catch(Exception ex) {
JOptionPane.showMessageDialog(this,
"Could not open the file.");
System.exit(1);
}
}
There is also a showSaveDialog() method you can call to display the standard save dialog.