Java Reference
In-Depth Information
JFileChooser fileChooser = new JFileChooser () ;
if ( f i leChooser . showDialog (NotepadFrame . this , "Save" )==
JFileChooser .APPROVEOPTION) {
File newFile = fileChooser . getSelectedFile() ;
try (PrintWriter fileWritter = new PrintWriter(newFile)) {
fileWritter .print(textArea.getText());
}
catch (Exception exception) {
}
}
}
} );
...
}
In the above example, the code textArea.getText() gets the whole text from the text
area. Even though this text can be multiple lines, it can be stored as a single string. Next,
we call the print method to write the text to the file.
The full version of the Notepad program is shown next.
import javax . swing . ;
import java .awt . ;
import java .awt. event . ;
import java . io . ;
import java . util . ;
public class Notepad {
public static void main(String [] args) {
NotepadFrame notepadFrame = new NotepadFrame () ;
notepadFrame . setVisible ( true );
}
}
class NotepadFrame extends JFrame
{
private static int WIDTH = 600;
private static int HEIGHT = 600;
{
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
setSize(WIDTH, HEIGHT);
final JTextArea textArea = new JTextArea () ;
public NotepadFrame ()
JMenuBar menuBar = new JMenuBar ( ) ;
setJMenuBar(menuBar) ;
JMenu fileMenu = new JMenu( "File" );
menuBar . add( f i leMenu ) ;
JMenuItem openMenuItem = new JMenuItem( "Open..." );
fileMenu . add(openMenuItem) ;
add( new JScrollPane(textArea) , BorderLayout.CENTER) ;
JPanel controlPanel = new JPanel () ;
controlPanel . setLayout( new FlowLayout(FlowLayout .LEFT) ) ;
String [ ] fontNames = GraphicsEnvironment .
getLocalGraphicsEnvironment () .
getAvailableFontFamilyNames () ;
final JComboBox fontComboBox = new JComboBox(fontNames) ;
 
Search WWH ::




Custom Search