| | | | | | | [文章信息] | | | 作者: | 务实 | | 时间: | 2004-04-26 | | 出处: | yesky | | 责任编辑: | 方舟 | |
| [文章导读] | | | 利用Jbuilder 9集成开发环境,用java语言实现一个具有读出、写入、编辑文本文件的编辑器 | |
| |
|
| | | |
|
|
|
|
|
3) 激活工具栏按钮
如果在应用向导中选择了Generate Toolbar(生成工具栏)选项,则Jbuilder就生成通常带有三个JButton 按钮(OPen File、Save File 和About) 控件且有图标显示的JtoolBar(工具栏)代码。要做的就是给每个按钮的标称指定文字和指定工具提示文字,并为每个按钮创建一个actionPerformed()事件,用户从每个按钮actionPerformed()事件中调用相应的事件处理方法。
指定按钮工具的提示文字
对应jButton1输入Open File 对应jButton2输入Save File 对应jButton3输入About
创建按钮事件
创建对应jButton1的jButton1_actionPerformed(ActionEvent e)事件并从中调用openFile()方法:
//Handle toolbar Open button openFile(); | 创建对应jButton2的jButton2_actionPerformed(ActionEvent e)事件并从中调用 saveFile()方法:
//Handle toolbar Save button saveFile(); 创建对应jButton3的jButton3_actionPerformed(ActionEvent e)事件并从中调用helpAbout()方法: //Handle toolbar About button helpAbout(); | 创建fileOpen()方法
fileOpen()方法的目的是执行当前在File|Open菜单项处理方法中的操作。即按下Open按钮和选择File|Open 菜单项执行的是同样的操作,所以创建fileOpen()方法将代码复制一下即可。从File|Open 菜单和Open按钮调用相同的代码。
// Handle the File|Open menu or button, invoking okToAbandon and openFile // as needed. void fileOpen() { if (!okToAbandon()) { return; } // Use the OPEN version of the dialog, test return for Approve/Cancel if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) { // Call openFile to attempt to load the text from file into TextArea openFile(jFileChooser1.getSelectedFile().getPath()); } this.repaint(); } | 创建saveFile()方法
对File|save菜单和save按钮再做一次同样的事情。将当前File|save事件处理器中的代码收集到新的 saveFile()方法中,即可从菜单处理器也可从按钮处理器对其调用。
// Save current file; handle not yet having a filename; report to statusBar. boolean saveFile() { // Handle the case where we don't have a file name yet. if (currFileName == null) { return saveAsFile(); } try { // Open a file of the current name. File file = new File (currFileName); // Create an output writer that will write to that file. // FileWriter handles international characters encoding conversions. FileWriter out = new FileWriter(file); String text = jTextArea1.getText(); out.write(text); out.close(); this.dirty = false; // Display the name of the saved directory+file in the statusBar. statusBar.setText("Saved to " + currFileName); updateCaption(); return true; } catch (IOException e) { statusBar.setText("Error saving " + currFileName); } return false; } | 建helpAbout()方法
对Help|About菜单和About按钮再做一次同样的事情。将当前Help|About事件处理器中的代码收集到新的 helpAbout()方法中,即可从菜单处理器也可从按钮处理器对其调用。
// Display the About box. void helpAbout() { TextEditFrame_AboutBox dlg = new TextEditFrame_AboutBox(this); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = getSize(); Point loc = getLocation(); dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,(frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true); dlg.show(); } |
|
|
|
|
|
|
|
|