Java graphical interface development of simple Notepad _java

Source: Internet
Author: User
Tags save file

After learning Java events, I wrote an extremely simple notepad. Controls such as Menubar,menu,menuitem are used, and events include ActionListener and KeyListener. The
code is as follows:

Package com.package3; 
 
* * Function: Simple notepad development, you can save the file, open the file, exit Notepad * author:ywq/import javax.swing.*; 
Import java.awt.*; 
Import java.awt.event.*; 
 
Import java.io.*; 
  public class MenuText {//Definition component: JFrame F;  MenuBar MB;    menu bar \ mu; 
  Menu JTextArea JTA;  MenuItem Openitem, SaveItem, Closeitem;  submenu FileDialog Opendia,savedia; 
   
   
  Pop-up Save and Open box file file; 
  Constructor public MenuText () {//Call initialization function init (); 
    ///initialization of the component public void init () {f=new JFrame ("Easy Notepad"); 
    Mb=new MenuBar (); 
    Mu=new Menu ("file"); 
    Openitem=new MenuItem ("open"); 
    Saveitem=new MenuItem ("Save"); 
    Closeitem=new MenuItem ("exit"); 
     
    Jta=new JTextArea (); 
     
    F.add (JTA); 
    Add Mu.add (Openitem); 
    Mu.add (SaveItem); 
     
    Mu.add (Closeitem); 
     
    Mb.add (MU); 
     
    F.setmenubar (MB); 
    Opendia=new FileDialog (F, "open", filedialog.load); 
Savedia=new FileDialog (F, "save", Filedialog.save);     
    Set JFrame properties F.setbounds (200, 300, 500, 400); 
    F.setdefaultcloseoperation (Jframe.exit_on_close); 
     
    F.setvisible (TRUE); 
     
  Invokes the Event function event (); 
    }//Event functions, handling Events public void event () {//Open option Openitem.addactionlistener (new ActionListener ()  
               
      {@Override public void actionperformed (ActionEvent e) {//Call Open File Method OpenFile (); 
     
    } 
       
       
    }); Save Option Saveitem.addactionlistener (new ActionListener () {@Override public void actionperformed (A 
       Ctionevent e) {//Invoke the method of saving the file.   
         
      SaveFile (); 
    } 
       
       
    }); Add an event for a text area, that is, press Ctrl+s to save//Because there are many ways to listen to the keyboard, and we only need one, so we can use the adapter keyadapter,//so that we need to implement one method jta.addkeylist Ener (New Keyadapter () {//keyboard down method public void keypressed (KeyEvent e) {if (E.iscontroldown () && E.getkeycode () = =keyevent.vk_s) {//Call method to save file.   
          SaveFile (); 
        Joptionpane.showmessagedialog (NULL, "right"); 
     
    } 
      } 
    }); Close option Closeitem.addactionlistener (new ActionListener () {@Override public void actionperformed ( 
         
      ActionEvent e) {//exit system System.exit (0); 
  } 
       
    }); The method for opening the text is public void OpenFile () {opendia.setvisible (true);//set its display/get the path and filename stri 
    ng Dirpath=opendia.getdirectory (); 
     
    String Filename=opendia.getfile (); 
     
    Prevent click to cancel error if (Dirpath==null | | filename==null) return; Jta.settext (""); Empty the text area file=new file (dirpath,filename); Creates a File object//reads data by row, appears in the text area try {bufferedreader br = new BufferedReader (new FileReader (file)) 
 
      ; 
 
      String line = null; 
   while ((Line=br.readline ())!=null) {jta.append (line+ "\ r \ n");   } br.close (); 
    catch (IOException ex) {throw new RuntimeException ("read failed"); 
  }///Save text method. 
       
      public void SaveFile () {///first determine if the file exists if (file==null) {savedia.setvisible (true); 
      String Dirpath = Savedia.getdirectory (); 
       
      String fileName = Savedia.getfile ();   
      Prevent click to cancel error if (Dirpath==null | | filename==null) return; Because the file does not exist.        
    So you need to create the file object file = new file (dirpath,filename); 
       
      //Writes data to file try {bufferedwriter bw=new bufferedwriter (new FileWriter (file)); String Info=jta.gettext (); Get the information of the text area bw.write (info); 
      Write operation Bw.flush (); 
       
    Bw.close (); 
    catch (IOException E1) {throw new RuntimeException (); 
  } public static void Main (string[] args) {//Create object New MenuText (); 

 } 
 
}

The results of the run are as shown in the figure:


The functions of this program are:

(1) You can open a file, and you can edit it.

(2) You can save the edited file.

(3) You can use Ctrl+s to save text

(4) You can click Closeitem to exit the program.

When function 3 is implemented , KeyListener is added to the text area, and the adapter keyadapter is used to implement the monitoring. But now the need for a combination of listening, that is, CTRL and S are pressed to trigger the save operation.

For combined listening, the Java API provides the appropriate method.

Find the direct parent class of the KeyEvent class, that is, the InputEvent class. As shown in the figure:


View the methods in the InputEvent class, as follows:


The object E of the subclass KeyEvent class of the InputEvent class can call the top method directly for judgment. The Iscontroldown () method is used to determine whether the CTRL key is pressed. if (E.iscontroldown () && e.getkeycode () = = keyevent.vk_s) in the program, the combination judgment is realized.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.