Building a Java text editor
JBuilder Foundation users skip this step and go to Step 6. Ignore any directions in the rest of this tutorial pertaining to the Edit|Font menu item or
FontChooser
dialog.
Let's get the FontChooser
dialog to interact with the font of textArea1
.
jMenuItem5_actionPerformed(ActionEvent e))
) that you just created.
Tip: To quickly locate this method in the source code, click the following node in the structure pane (bottom left of the AppBrowser). Note that the order of the elements in your structure pane might not appear exactly as they do here; the order depends on the setting of the Structure Order options on the Java Structure page of the Structure View Properties dialog box.
jMenuItem5
) event handling method between the opening and closing curly braces, being sure to replace the old fontChooser1.showDialog();
code:
// Handle the "Edit Font" menu item // Pick up the existing font from the text area // and put it into the FontChooser before showing // the FontChooser, so that we are editing the // existing / previous font. fontChooser1.setSelectedFont(jTextArea1.getFont()); // Obtain the new Font from the FontChooser. // First test the return value of showDialog() to // see if the user pressed OK. if (fontChooser1.showDialog()) { // Set the font of jTextArea1 to the font // the user selected before pressing the OK button jTextArea1.setFont(fontChooser1.getSelectedFont()); } //repaints menu after item is selected this.repaint(); //Repaints text properly if some text is highlighted when font is changed. jTextArea1.repaint();
The entire method should look like this:
void jMenuItem5_actionPerformed(ActionEvent e) { // Handle the "Edit Font" menu item // Pick up the existing font from the text area // and put it into the FontChooser before showing // the FontChooser, so that we are editing the // existing / previous font. fontChooser1.setSelectedFont(jTextArea1.getFont()); // Obtain the new Font from the FontChooser. // First test the return value of showDialog() to // see if the user pressed OK. if (fontChooser1.showDialog()) { // Set the font of jTextArea1 to the font // the user selected before pressing the OK button jTextArea1.setFont(fontChooser1.getSelectedFont()); } //repaints menu after item is selected this.repaint(); //Repaints text properly if some text is highlighted when font is changed. jTextArea1.repaint(); }
In this application, the font for the entire text area (not just the selected text) is changed. Don't expect the font settings to persist. We aren't going to enter code to enable that feature.