Develop a text editor with JBuilder 9

zhaozj2021-02-12  137

1. Overview Text Editor is the most common application. Here we use the JBuilder 9 integrated development environment, implement a simple text editor in Java language. This text editor has a read, write, edit text file, which sets basic features such as text color, glyph, and editing area background color.

We first create items through the JBuilder 9 Item Wizard and Application Wizard, then apply visual design tools, modify UI design, connect events, editing source, and common controls and tasks such as common controls and tasks such as menu items, toolbars, text areas and system events. Treatment. It is involved in specific technologies:

Use the JFilechooser dialog to let users choose a text file.

Read, write and process text in text files with Jtextarea.

Set the foreground color and background colors.

Set the font with the dbswing fontchooser dialog. Display information in the status bar and window title bar. Handmade the code that handles the UI event.

By placing the code in a new Help method that can be called by the two event processors that can be called by the men's item and the button, make the menu item and the buttons perform the same code. Add a right-click menu to the JTextArea control. Keep the tracking of the file and whether the file is active, show the file | New, File | Open, File | Save, File | Save, Edit, and Exit Logic. Expand the "Text Editor" application as JAR file.

Second, the Development Text Editor Java Source Description Text Editor Program contains three Java source programs, TEXTEDITFRAME.JAVA, TEXTEDITCLASS.JAVA, and TEXTEDITFRAME_ABOUTBOX.JAVA programs, which will be described below: 1, TextEditFrame.java source code code ( Extraction section):

Package texteditor; // texteditframe.javaimport java.awt. *; // Imported IMPORT JAVA.AWT.EVENT. *; Import Javax.swing. *; Import com.borland.dbswing. *; import java.io. *; . import javax.swing.text *; import javax.swing.event *; public class TextEditFrame extends JFrame {IntlSwingSupport intlSwingSupport1 = new IntlSwingSupport (); // Swing of Internet control: i.e., localized application to the need to add a line Swing control JFilechooser // and JColorchooser appears in the language running language JPanel ContentPane; // Setting the content window (Contentpane) JPanel control JMenuBar MenuBar1 = new jmenubar (); // Create a menu bar and add JMenu Menufile in the Framework Form = New jMenu (); // Create a File menu and the corresponding menu item jMenuItem menufileExit = new jMenuitem (); jMenu menuhelp = new jMenu (); // Create a Help menu and the corresponding menu item jMenuitem menuhelPabout = new jMenuitem (); JToolBar Toolbar = new JTOOLBAR (); // Create toolbar component jButton jbutton1 = new jButton (); // creation button component jButton jButton2 = new jbutton (); jbutton jbutton3 = new jbutton (); imageicon image1; // Define icon ImageICON image2; imageicon image3; jlabel statusbar = new jlabel (); // Create tag component borderLayout borderLayout1 = new borderLayout (); // Create BorderLayout Format JscrollPane Jscroll Pane1 = new jscrollpane (); // Create a scroll window control Jtextarea jtextarea1 = new jtextarea (); // Create multi-line text domain component JMenuItem jMenuitem1 = new jMenuItem (); // Create a menu item JMenuItem (); JMenuItem jMenuItem3 = new JMenuItem (); JMenuItem jMenuItem4 = new JMenuItem (); FontChooser fontChooser1 = new FontChooser (); // create a font selection dialog JMenu jMenu1 = new JMenu (); JMenuItem jMenuItem5 = new JMenuItem (); JMenuItem jMenuItem6 = new JMenuItem (); JMenuItem jMenuItem7 = new JMenuItem (); JFileChooser jFileChooser1 = new JFileChooser (); // create a text selection dialog String currFileName = null;. // Full path with filename null means new / untitled.boolean dirty = False; Document Document1;

// Text DBTextDataBinder dBTextDataBinder1 = new DBTextDataBinder (); // True means modified text.// rack frame configured public TextEditFrame () {enableEvents (AWTEvent.WINDOW_EVENT_MASK); try {jbInit (); updateCaption ();} catch (Exception e ) {E.PrintStackTrace ();}} // Component initializes private void jbinit () throws exception {// three toolbar button icon image1 = new imageicon (TextETFrame.class.getResource ("OpenFile.gif"); image2 = New ImageCon ("CloseFile.gif"); image3 = new imageicon ("Help.gif"); ContentPane = (JPANEL) this.getContentPane (); // Content formal document1 = jtextarea1.getdocument (); // Multi-line text domain document contentpane.setLayout (borderLayout1); // borderlayout layout this.setsize (New Dimension (400, 300)); // Window Size this.Settitle ( "Text Editor"); // window title statusBar.setText ( ""); menuFile.setText ( "File"); menuFileExit.setText ( "Exit"); menuFileExit.addActionListener (new TextEditFrame_menuFileExit_ActionAdapter (this)); // Add event listener Menuhelp.Settext ("Help"); menuhelpabout.settext ("about"); menuhelp About.addActionListener (new TextEditFrame_menuHelpAbout_ActionAdapter (this)); jButton1.setIcon (image1); // set three toolbar button icons, add event listeners jButton1.addActionListener (new TextEditFrame_jButton1_actionAdapter (this)); jButton1.setToolTipText ( "Open File "); jButton2.setIcon (image2); jButton2.addActionListener (new TextEditFrame_jButton2_actionAdapter (this)); jButton2.setToolTipText (" Close File "); jButton3.setIcon (image3); jButton3.addActionListener (new TextEditFrame_jButton3_actionAdapter (this)); jButton3 .SetTooltiptext ("About"); jtextarea1.setLineWrap (true); jtextarea1.setwrapstyleword (true); jtextarea1.setBackground (color.white);

jMenuItem1.setText ( "New"); // setup menu, add an event listener jMenuItem1.addActionListener (new TextEditFrame_jMenuItem1_actionAdapter (this)); jMenuItem2.setText ( "Open"); jMenuItem2.addActionListener (new TextEditFrame_jMenuItem2_actionAdapter (this)); jMenuItem3 .setText ( "Save"); jMenuItem3.addActionListener (new TextEditFrame_jMenuItem3_actionAdapter (this)); jMenuItem4.setText ( "Save As"); jMenuItem4.addActionListener (new TextEditFrame_jMenuItem4_actionAdapter (this)); fontChooser1.setFrame (this); fontChooser1.setTitle ( "Font"); jMenu1.setText ( "Edit"); jMenuItem5.setText ( "Font"); jMenuItem5.addActionListener (new TextEditFrame_jMenuItem5_actionAdapter (this)); jMenuItem6.setText ( "Foreground Color"); jMenuItem6.addActionListener (new TextEditFrame_jMenuItem6_actionAdapter (this)); jMenuItem7.setText ( "Background Color"); jMenuItem7.addActionListener (new TextEditFrame_jMenuItem7_actionAdapter (this)); document1.addDocumentListener (new TextEditFrame_document1_documentAdapter (this)); dBTextDataBinder1.setJTextComponent (jT extArea1); // Turn off right-click file Open ... menu item dBTextDataBinder1.setEnableFileLoading (false);. // Turn off right-click file Save ... menu item dBTextDataBinder1.setEnableFileSaving (false);. toolBar.add (jbutton1); // Tool component Add button Toolbar.Add (jButton2); toolbar.add (jButton3); menufile.add (jMenuitem1); // Menu component Add menu item menufile.add (jMenuitem2); menufile.add (jMenuitem3 ); Menufile.add (jMenuitem4); menufile.addseParator (); // single component adds a spacing menufile.add (menufileexit); menuhelp.add (menufile); menubar1.add (jMenu1) MenuBar1.Add (Menuhelp); this.setjmenubar (Menubar1); ContentPane.Add (Toolbar, BorderLayout.North);

// content window is provided borderLayout placer contentPane.add (statusBar, BorderLayout.SOUTH); contentPane.add (jScrollPane1, BorderLayout.CENTER);. JScrollPane1.getViewport () add (jTextArea1, null); jMenu1.add (jMenuItem5); jMenu1.add (jMenuItem6); jMenu1.add (jMenuItem7);} // 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 ();} texteditframe.java is the primary program for implementing the text editor, which has 6-point programming skills description: 1) Make a completely full user interface top menu bar and the bottom status bar The layout manager of the main user interface container of the text area needs to use the borderlayout. In the main container, a JPANEL control called the content window is changed to the boundary layout, which is only required to add a text area control in the content window. To do this, first add a scroll window in the content window, and then put the text area control (JTextArea) in the scroll window. The scroll window provides a text area with rolling bats (JSCOLLPANE). A boundaries of a boundary layout are divided into five areas: North, South, East, West, China. Each area can only have a control, so you can have five controls (Note: panel containing multiple controls is considered a control). The control of the central area is fully accounted for the container control, which is not occupied by any other area containing the control. For example, in this example, the toolbar occupies the North District (top), the status bar occupies the southern area (low), because the two regions have no controls, so that the rolling window control occupies the center area and expands to the left of the container (West ) The edge of right (east). 2) Creating a menu file (including New, Open, Save, Save AS, and EXIT menu items), menu edit {contains font (font), Foreground, and Background menu item} and menu HELP (included About Help Description) 1 Menu Edit's Font (Font), Foreground (Prospect)] and Background (Background Color) menu item: Add a Dictionary Selection dialog box to the menu, start from the Edit | Font menu item, this menu will lead A Fontchooser dialog box. Add a menu item (source program) to Fontchooser (source program) as follows:

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 change. Jtextarea1.repaint ();} To jcolorchooser Additional Menu item Events Create Edit | Foreground and Edit | Background Two menu events, and Connect them with the JColorchooser dialog control in Swing.

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 instance item is successd this.repaint ();

2 Menu File NEW, OPEN, SAVE, SAVE AS, and EXIT menu item: Add the test file to be modified by the code program that needs to keep track of the file being generated, open, or saved whether it is modified ("dirty"), so You can prompt to ask if you want to save your operation when you turn off your file or exit. To this end, a Boolean variable called Dirty is added. Add the following OkToabandon () method to the source code, this new method can be backed up after SaveAsFile () method: // check if file is dirty.//iffs? Yes / no / cancel "decision.boolean okToAbandon () {int value = JOptionPane.showConfirmDialog (this,"? Save changes "," Text Edit ", JOptionPane.YES_NO_CANCEL_OPTION); switch (value) {case JOptionPane.YES_OPTION: // yes, please save changes Return savefile (); case joptionpane.no_option: // no, Abandon Edits // IE returnire without saving return.cancel_option: default: // Cancel Return False;}}

The above method will be called when the user selects File | New, File | Open, or File | EXIT is called. The purpose of this method is to test whether the text needs to be saved (whether it is moving). If the text is moving, this method uses Yes, NO, and the CANCEL message to ask if the user is saved. This method also calls SaveFile when the user is selected as the YES button. If the Boolean value returned by this method is True (true), it indicates that the current file can be exited because the file is clean or the user point is selected the YES or NO button. If the return value is false (fake), it means that the user selects Cancel. The actually checking whether the file is changed to add in the subsequent steps. At present, this method always believes that the document is not clean, even if the text is not passive. Then add a method of setting the Dirty variable to true when the user enters text in text area, and adds the code to test the DIRTY variable at the header of the oktoabandon () method. Add a menu event processor that clears the text area pends the File | New menu item with the event processor that clears the text area.

void jMenuItem1_actionPerformed (ActionEvent e) {// Handle the File | New menu item if (okToAbandon ()) {// clears the text of the TextArea jTextArea1.setText ( "");. // clear the current filename and set the file as clean: currfilename = null; dirty = false; UpdateCaption ();}}

Add a file selection dialog to hang the event processor for the JFilechooser control provided to the user a file selection dialog box. If the user selects a file, press the OK button, this event processor opens the text file and puts the text into the Jtextarea (ie text area).

void jMenuItem2_actionPerformed (ActionEvent e) {// Handle the File | Open menu item 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 ());.};} Add read out from the file this.repaint () The code of the text adds the code to the text area Jtextarea from the selected file. First, you need to add a new method to add a new method to perform the actual opening file, which is called OpenFile ().

// Open named file; read text from file Into jtextarea1; report to status bar.void OpenFile (String filename) {Try {// Open a file of the given name. File File = New File (filename); // Get the size Of the opened file. int size = (int) file.length (); // set to zero a counter for counting the number of // characters That Have been = 0; // Create An Input reader based on the file, so we can read its data // FileReader handles international character encoding conversions FileReader in = new FileReader (file);.. // Create a character array of the size of the file, // to use as a Data Buffer, Into Which We Will Read // Text Data. Char [] Data = New Char [Size]; // Read All Available Characters INTO The Buffer. While (In.ready ()) {// Increment The Count For Each Character Read, // and Accumulate Them in the data buffer. Chars_read = in.read (data, chars_read, size - chars_read);} in.close (); // Create a Temporary String Containing th e data, // and set the string into the JTextArea jTextArea1.setText (new String (data, 0, chars_read));.. // Display the name of the opened directory file in the statusBar statusBar.setText ( "Opened" filename);} catCH (IOException E) {status bar.settext ("Error Opening" filename);}} Replace the IF () statement in the previously said FILE | OPEN Event Processor:

// Display the name of the opened directory file in the statusBar.statusBar.setText ( "Opened" jFileChooser1.getSelectedFile () getPath ().); // Code will need to go here to actually load text // from file into JTextArea.with this new openFile () method instead, using the concatenated Directory and File name // Call openFile to attempt to load the text from file into JTextAreaopenFile (jFileChooser1.getSelectedFile () getPath ().);. // repaints menu After item is self-hepaint (); Add a Save File Menu item writes the file back to the disk of the disk when selecting File | Save and File | Save AS. To this end, it is necessary to add a string routine variable containing the name of the file name and add a method to write text back to the file or another file. Create the following methods available from the File | Save Event Processor SaveFile (). It can be placed after the OpenFile () method. This method also writes the file name to the status bar when saving.

// Save current file; Handle Not Yet Having a filename; Report to Statusbar.Boolean Savefile () {// Handle The Case Where We don't have (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 = jtext (); out.write (text); out.close (); this.dirty = false; // display the name of the saved directory file in the statusbar. statusbar.setTextTextTextTextText ("Saved to" currfilename); return true;} catch (ioException e) {status bar.settext ("Error Saving" CurrFileName);} Return False;}

Creating a saveasfile () method called from the SaveFile () method when creating a current file name. It can also be called from the FILE | SAVE AS menu. Targe the following code after the SaveFile () method:

// Save current file, asking user for new destination name.// Report to statuBar.boolean saveAsFile () {// Use the SAVE version of the dialog, test return for Approve / Cancel if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog (this)) {// Set the current file name to the user's selection, // then do a regular saveFile currFileName = jFileChooser1.getSelectedFile () getPath ();. // repaints menu after item is selected this.repaint (); Return Savefile ();} else {this.repaint (); return false;}} menu file | EXIT, the code in exiting the application is as follows:

// File | EXIT ACTION PerformedPublic Void JmenufileExit_ActionPerformed (ActionEvent E) {IF (Oktoabandon ()) {System.exit (0);}}

3) Activation toolbar button If you select the Generate Toolbar option in the Apply Wizard, JBuilder generates JToolbar that usually has three JButton buttons (Open File, Save File, and About) control and icon displayed. Bar) code. What to do is to specify a text and specify the nominal of each button and a specified tooltip, and create an actionPerformed () event for each button, and the user calls the corresponding event processing method from each button actionPerformed () event. Specify button Tool Corresponding JBUTTON1 Enter Open File Corresponding to JButton2 Entering Save File Creating a JButton3 Entering About Creating a Button Event Create a JButton1_ActionPerformed (ActionEvent E) event corresponding to jButton1, call OpenFile () method:

// Handle Toolbar open buttonopenfile ();

Create a jButton2_ActionPerformed (ActionEvent E) event corresponding to jButton2 and call the savefile () method:

// Handle Toolbar Save ButtonsaveFile (); Create a jButton3_ActionPerformed (ActionEvent E) event corresponding to JButton3 and call Helpabout (): // Handle Toolbar About ButtonHelPabout ();

The purpose of creating a fileOpen () method fileopen () method is to perform the operation currently in the File | Open menu item processing method. That is, press the OPEN button and select the File | Open menu item to execute the same operation, so create a fileOpen () method to copy the code. From the File | Open menu and the Open button to call the same code.

// Handle The File | Open Menu or Button, Invoking Oktoabandon and OpenFile // AS NEED.void FileOpen () {ix;} // 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 () Create a SaveFile () method to the File | Save menu and Save button again. Collect the code in the current File | Save event processor to a new SaveFile () method, you can call from the menu processor from the button processor.

// Save current file; Handle Not Yet Having a filename; Report to Statusbar.Boolean Savefile () {// Handle The Case Where We don't have (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 = jtext (); out.write (text); out.close (); this.dirty = false; // display the name of the saved directory file in the statusbar. statusbar.setTextTextTextTextText ("Saved to" currfilename); updateCaption (); return true;} catch (ooexception e) {status bar.settext ("Error Saving" currfilename);} returnaf

Built the helpabout () method to do the same thing to the Help | About menu and the About button. Collect the code in the current Help | About event processor to the new Helpabout () method, you can also call from the menu processor from the button processor.

// 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 ();} 4) Processing Event Processing Contributing to text districts linking event processing with text area JtexTarea, so as long as you have an input operation user program, set the dirty flag as true. For this purpose, you need to add a SWING control DocumentListener (text listener) to the JTextArea's text template and check the incident, delete, and change. DocumentListener is added to jbinit ():

Document1.addDocumentListener (New TEXTEDITFRAME_Document1_Documentadapter (this));

Insert the following code in the void document1_changedupdate (DocumentEvent E) event:

DIRTY = TRUE;

Create two events for Document1: INSERTUPDATE () and transoveUpdate (). Insert the same code used in the ChangeDUpdate () event in these events. This will force the Dirty flag to be true as long as you enter any character in the text area. 5) Add a right-click pop-up menu control in the text area DBTextDatabase to add an right-click menu to add a simple editing task such as cut, copy, paste, etc. in the Swing text control. DBTextDataBinder has a file that loads files into JTextArea and saves files, but does not allow users to recover file names that are displayed or saved in the status bar. In this example, just add a DBTextDataBinder control to jtextArea1, not using files to open and save operations. 6) Display the current file name and when the file is displayed when the file is "contaminated" when the file is "polluted". To do this, create a new method for updating the title bar, then call it from the code to change the file name or change the dirty flag. Try this new method to updateCAPTION (). UpdateCaption () method:

// Update the title bar of the application to show the filename and its dirty state.void updateCaption () {String caption;. If (currFileName == null) {// synthesize the "Untitled" name if no name yet caption = " Untitled ";} else {caption = currfilename;} // address}} // add a" * "} {caption =" * " caption;} caption =" text editor - " CAPTION This.SetTitle (CAPTION);} Call UpdateCaption () when the Dirty flag is actually changed or whenever the user changes the current file name currfilename. In particular, the UpdateCaption () statement is to be called in the following places: 1 After the texteditframe () constructor is adjusted to call the jbinit () method within the TRY module; 2 at the last line of the TRY module of the openfile () method; 3 in Savefile () Method The TRY module returns the front line of TRUE; 4 at the last line of the IF module of the File | New menu processor jMenuitem1_actionperformed (); 5 When the user input, the Dirty flag is set to true in a clean file. . Each text event processor should change to:

void document1_changedUpdate (DocumentEvent e) {if {dirty = true (dirty!); updateCaption ();}} void document1_insertUpdate (DocumentEvent e) {if {dirty = true (dirty!); updateCaption ();}} void document1_removeUpdate (DocumentEvent e) {if (! dirty) {dirty = true; UpdateCaption ();}}

2, TextEditclass.java source code:

Package textEditor; import javax.swing.uimanager; import java.awt. *; / ***

Title: TextEditor *

description: this is a study programme *

Copyright: Copyright (c) 2004 *

Company: ghq * @author ghq * @version 1.0 * / public class TextEditClass {boolean packFrame = false; // Construct the application public TextEditClass () {TextEditFrame frame = new TextEditFrame (); // Validate frames that have preset sizes // Pack frames that have useful preferred size info, eg from their layout if (packFrame) {frame.pack ();} else {frame.validate ( );} // Center the window Dimension screenSize = Toolkit.getDefaultToolkit () getScreenSize ();. Dimension frameSize = frame.getSize (); if (frameSize.height> screenSize.height) {frameSize.height = screenSize.height;} if (frameSize.width> screenSize.width) {frameSize.width = screenSize.width;} frame.setLocation ((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); frame .SetVisible (TRUE) ;} // Main method public static void main (String [] args) {try {UIManager.setLookAndFeel (UIManager.getCrossPlatformLookAndFeelClassName ());} catch (Exception e) {e.printStackTrace ();} new TextEditClass ();} }

The above program is mainly to build the main window and main method entry (main ()) of TextEditorFrame (main ()), and it has 2 points programming skills. The base tone changes from its default value, before starting using the UI designer, let the UI designer use Metal Look & FEEEL within JBuilder, or other appearances and tones can also be used, but in this case Appearance and tone, at this time a choice suitable for cross-platform design. Runtime appearance and basetons do not have any impact on the user interface (UI) of the Designer's pop-up menu or the JBuilder Environmental Options dialog box. To force a runtime appearance and tone, you must set in the main method of the application (this example is the class ()) class (main ()). As a default, the Application Wizard generates the following line code in the MAIN () method of the run class: UIManager.SetLookandFeel (UIManager.getsystemLookandFeelClassName ());

Its meaning is the appearance of the operating time of operation using the appearance of the host system. If the appearance of the CDE / MotiF or Windows, the parameters should be changed to:

UIManager.SetLookandFeel ("com.sun.java.swing.plaf.motiflookandfeel"); or UIManager.SetLookandFeel ("com.sun.java.swing.plaf.windows.windowslookandfeel");

2) Definition of the window

Dimension screenSize = Toolkit.getDefaultToolkit () getScreenSize ();. Dimension frameSize = frame.getSize (); if (frameSize.height> screenSize.height) {frameSize.height = screenSize.height;} if (frameSize.width> screenSize. Width) {framesize.width = screensize.width;} frame.setlocation (Screensize.width - framesis.width) / 2, (Screensize.Height - framesis.Height) / 2); frame.setVisible (TRUE);

3, TextEditFrame_AboutBox.java source code:

Package texteditor; import java.awt. *; import java.awt.Event. *; import javax.swing. *; import javax.swing.border. *; / ***

title: texteditor *

description: this is a study programme *

Copyright: Copyright (c) 2004 *

Company: GHQ * @Author ghq * @version 1.0 * / public class TextEditFrame_AboutBox extends JDialog implements ActionListener {JPanel panel1 = new JPanel (); JPanel panel2 = new JPanel (); JPanel insetsPanel1 = new JPanel (); JPanel insetsPanel2 = new JPanel (); JPanel insetsPanel3 = new JPanel (); JButton button1 = new JButton (); JLabel imageControl1 = new JLabel (); imageIcon imageIcon; JLabel label1 = new JLabel (); JLabel label2 = new JLabel (); JLabel label3 = new JLabel (); JLabel label4 = new JLabel (); BorderLayout borderLayout1 = new BorderLayout (); BorderLayout borderLayout2 = new BorderLayout (); FlowLayout flowLayout1 = new FlowLayout (); FlowLayout flowLayout2 = new FlowLayout (); GridLayout gridLayout1 = new GridLayout (); String product = "TextEditor"; String ve rsion = "1.0"; String copyright = "Copyright (c) 2002"; String comments = "This is a study programme"; // Construct the frame public TextEditFrame_AboutBox (Frame parent) {super (parent); enableEvents (AWTEvent.WINDOW_EVENT_MASK ); try {jbInit ();} catch (Exception e) {e.printStackTrace ();} pack ();} // Component initialization private void jbInit () throws Exception {//imageLabel.setIcon(new ImageIcon (TextEditFrame_AboutBox. Class.getResource ("[Your Image])));

this.setTitle ( "About"); setResizable (false); panel1.setLayout (borderLayout1); panel2.setLayout (borderLayout2); insetsPanel1.setLayout (flowLayout1); insetsPanel2.setLayout (flowLayout1); insetsPanel2.setBorder (new EmptyBorder (10 , 10, 10, 10)); GridLayout1.seTROWS (4); GridLayout1.SetColumns (1); label1.settext (product); label2.settext (version); label3.settext (copyright); label4.settext (Comments) INSETSPANEL3.SetLayout (GridLayout1); INSETSPANEL3.SETBORDER (New Emptyborder (10, 60, 10)); Button1.Settext ("OK"); Button1.AddActionListener (this); INSETSPANEL2.ADD (ImageControl1, null); Panel2.add (INSETSPANEL2, BORDERLAYOUT.WEST); this.getContentPane (). add (panel1, null); INSETSPANEL3.ADD (label1, null); INSETSPANEL3.ADD (label2, null); INSETSPANEL3.ADD (label3, null) ; insetsPanel3.add (label4, null); panel2.add (insetsPanel3, BorderLayout.CENTER); insetsPanel1.add (button1, null); panel1.add (insetsPanel1, BorderLayout.SOUTH); panel1.add (panel2, BorderLayout.NORTH } // Overri dden so we can exit when windows is cancelprotected void processWindowEvent (WindowEvent e) {if (e.getID () == WindowEvent.WINDOW_CLOSING) {cancel ();} super.processWindowEvent (e);} void cancel () {dispose ( );} // Help | About de Button IS used action PerformedPublic void actionPerformed (E.GetSource () == Button1) {Cancel ();}}} Description: The above program is mainly built The AboutBox dialog of the Help menu, display products, etc., etc.. To this end, we have completed all menus and code designs such as text editors, and the Text Editor window appears in the JBuilder9 environment.

Third, running the package from the command line For the instructions First, the Text Editor application is equipped into a JAR file. Since the "Text Editor" application has created, users can use JBuilder9 Archive Builder to assemble all files into a Java Archive File (JAR, Java archive). Before running the application from the command line, the user must ensure that the PATH environment variable of the operating system points to the JDK JRE / BIN / directory, the Java's operating environment. The JBuilder9 installation process guarantees that JBuilder9 knows where the JDK class file is found there. But if you leave the JBuilder9 environment, the system needs to know when running Java, what location file is installed. How to set the operating system used by the PATH environment variable user. To run the Text Edit program from the command line, the steps are as follows: 1 Switch to the command line window and change the path to the TextEditor directory where the JAR file is located. 2 Enter Java in the command line to see if Java is in the current path, if the Java usage and options will be displayed, if not, set the PATH environment variable to the JDK JRE / BIN / folder. For Windows XP and NT / 2000/2003, the set path is as follows: set path = / / / jre / bin here: is the drive; is a jbuilder9 directory name is the JDK directory name provided during JBuilder installation, for example: JBuilder9 / JDK1.4 / 3 Enter the following command at the command line: java -jar Texteditor.jar

Here:

Java ---- Java tool running Java files.

JAR ---- This option tells the Java VM (Java Virtual Machine) This is a packaging file.

TextEditor.jar ---- The name of the package file.

Since the list file provides the class in the main-class header, there is no need to specify a class name at the end of the command line, and because all classes, resources, and independence are included in the JAR file assembled, it is also You don't need to specify a class path ClassPath or copy the JBuilder library file to the current directory.

Note: Once the -jar option is used, the Java is running ignored any explicit ClassPath settings.

If we are not running this JAR file in the TextEditor directory, you should use the following java commands:

Java -jar -classpath

Java is running in the JAR file in the JAR file. Other classes used, the Java VM virtual machine uses three search path to find files, which are: boot class paths, installation time expansion paths and user class paths.

转载请注明原文地址:https://www.9cbs.com/read-7531.html

New Post(0)