TextEditFrame.java 是实现文本编辑器的主要程序,它有下面6点编程技巧说明:
1) 制作一个完全充满用户界面顶部菜单栏和底部状态栏之间区域的文本区
主用户界面容器的布局管理器需要采用边界布局(Borderlayout)。在主容器中,含有一个叫做内容窗(contentPane)的JPanel 控件,被改变成边界布局,需要做的只是在内容窗添加一个文本区控件。为此,先在内容窗添加一个滚动窗,再在滚动窗内放上文本区控件(jTextArea)。滚动窗提供一个带滚动棒(JScollPane)的文本区。
一个边界布局的容器被分成五个区域:北、南、东、西、中。每个区域只能有一个控件,所以最多可有五个控件(注:含有多个控件的面板被认为是一个控件)。放进中心区域的控件完全占满该容器控件,不被含有控件的任何其他区域所占据。例如,在本例中,工具栏占据北区(顶),状态栏占据南区(低步),由于东西两个区域没有安排控件,这样滚动窗控件占据中心区域并扩展到容器的左(西)右(东)的边缘。
2) 创建菜单File (包含New、Open、Save、Save as 和Exit菜单项),菜单Edit{包含Font(字体)、Foreground(前景色)和Background(背景色)菜单项} 和菜单Help (包含About帮助说明)
①菜单Edit的Font(字体)、Foreground(前景色)和Background(背景色)菜单项:
添加字型选择对话框
给菜单挂上事件,从 Edit|Font 菜单项开始,该菜单将引出一个FontChooser (字型选择)对话框。 给FontChooser附加一个菜单项事件(源程序)如下:
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(); } | 给JcolorChooser(颜色选择)附加一个菜单项事件
创建Edit|Foreground and Edit|Background两个菜单事件,并将它们与Swing中的JcolorChooser对话控件连接起来。
void jMenuItem6_actionPerformed(ActionEvent e) { // Handle the "Foreground Color" menu item Color color = JColorChooser.showDialog(this,"Foreground Color",jTextArea1.getForeground()); if (color != null) { jTextArea1.setForeground(color); } //repaints menu after item is selected this.repaint(); } void jMenuItem7_actionPerformed(ActionEvent e) { // Handle the "Background Color" menu item Color color = JColorChooser.showDialog(this,"Background Color",jTextArea1.getBackground()); if (color != null) { jTextArea1.setBackground(color); } //repaints menu after item is selected this.repaint(); } |
|
|