Java Career - Java Foundation - GUI

Keywords: Java Windows JDK IE

Lecture 1: GUI (User Graphic Interface)

I. overview

1. GUI: Graphical User Interface (GUI), a graphical user interface, is a way for computers to interact with users.

2. Two ways of computer-user interaction: GUI and CLI

GUI: Graphical User Interface, Graphical User Interface, graphical user interface, to display the computer operation interface, convenient and intuitive.

CLI: Command Line User Interface, Command Line User Interface, Command Line User Interface, which is a common Dos command line operation, must remember some commands, the operation is not intuitive.

3. Java also encapsulates this interface as an object, in which the objects are placed in two packages: the java.Awt package and the javax.Swing package.

The java.Awt package: Abstract Window Toolkit, or abstract window toolkit. To call the local system method to realize the function, it is a heavyweight control.

Javaax.Swing package: A set of graphical interface system based on AWT, which provides more components and is completely implemented by java, enhances portability and is a lightweight control.

 

II. Succession Diagram

 

Container For containers, it is a special component in which other components can be added through the add method.

Container Common Subclass: Window Panel.

Common subclasses of Window s: Frame Dialog

 

3. Layout Manager

1. Layout: Component Arrangement in Containers

2. Common layout managers:

FlowLayout: Flow Layout: Flow Layout Manager. Arrange from left to right, which is the default layout manager for Panel

BorderLayout: BorderLayout, the border layout manager, is the default layout manager for Frame. If there is only one component in the form, the entire form will be covered.

3) GridLayout: Grid Layout Manager, Rule Matrix

CardLayout: Card Layout: Card Layout Manager, Tab

5) GridBayLayout: Grid Packet Layout Manager, Irregular Matrix

3. If there are many layout modes, how to create the form interface? Steps:

1) First divide the form Frame into large areas, set up its layout manager, and add panel panel Panel.

2) Add components to Panel and set the layout manager of panel.

 

4. Simple Form Creation Process

1. Create Frame Form:

Frame f = new Frame("my Frame"); // Caption can be set, that is, form name

2. Basic settings for forms: size, location, layout, etc.

f.setSize(int wight,int hight); //Form size settings

f.setLocation(int x,int y); //Form Display Position Settings, Lateral and Longitudinal Coordinates

f.setBounds(int x,int y,int wight,int hight) can also be used directly to set size and location

f.setLayout(Layout layout), with parameters specified for layout managers, such as FlowLayout

3. Define components:

For example, Button b = new Button("my Button"); and // the name of the configurable component

4. Adding components to a form through the form's add method:

f.add(b); //Add button components to forms

5. Let the form display:

f.setVisible(boolean b); // Whether the form is displayed by setting whether the parameter is true or false

Example:

  1. <span style="font-size:14px;">import java.awt.*;  
  2.   
  3. class AwtFirstDemo   
  4. {  
  5.     public static void main(String[] args)   
  6.     {  
  7.         //Create Frame Form:  
  8.         Frame f = new Frame("my Frame");//Settable title  
  9.   
  10.         //Basic settings for forms: size, location, layout, etc.  
  11.         f.setSize(500,100);//Form Size Settings  
  12.         f.setLocation(300,150);//Form Display Position Settings, Lateral and Longitudinal Coordinates  
  13.   
  14.        //f.setBounds(int x,int y,int wight,int hight); //You can also use this method directly to set size and location  
  15.           
  16.         f.setLayout(new FlowLayout());//The parameter is the specified layout manager, such as FlowLayout  
  17.           
  18.         //Define components:  
  19.         Button b = new Button("my Button");//Name of Settable Component  
  20.           
  21.         //Add components to a form through the form's add method:  
  22.         f.add(b);//Add the button component to the form  
  23.           
  24.         //Let the form display:  
  25.         f.setVisible(true);//Whether the form is displayed by setting whether the parameter is true or false  
  26.     }  
  27. }  
  28.   
  29. </span>  


V. Event Monitoring Mechanism

1. Composition:

1) Event source (component): GUI components in awt or swing packages

Event: Each event source has its own unique corresponding and common events

3) Listener: Encapsulate actions that trigger an event (more than one action) into the listener.

4) Event handling: the way to deal with events after they are triggered.

 

2. Instructions for Use

The first three components have been defined in java and can be used directly by capturing their objects. What we need to do is to process the generated actions.

Steps:

1) Identify the source of the event (container or component). The listener is registered on the event source by the addXXXListener() method of the event source object. This method receives subclass objects of XXXListener, or subclass objects of XXXAdapter, a subclass of XXXListener.

2) Generally expressed by anonymous inner classes. When overriding a method, the parameters of the method are generally accepted by variables of type XXXEvent.

Such as:

  1. f.addWindowlistener(new WindowAdapter()  
  2. {  
  3.      public void windowClosing(WindowEvent e)  
  4.      {  
  5.           System.exit(0);//Represents closing windows  
  6.      }  
  7. });  

Explain:

1) When an event is triggered, it is packaged as an object and passed to the variable of the parameter in the replication method. Including event source objects. Get it through getSource() or getComponent().

2) If you use subclasses to implement the Windows Listener interface, you need to override seven of these methods. You can only use the closing action in them. Other actions are not used, but you have to rewrite all of them. Because Windows Adapter, a subclass of Windows Lister, has implemented this interface and covered all of its methods. Then just inherit the Windows Adapter and override the required methods.

3) Identify events and process them. In fact, adding any listener requires adding any event.

Example:

  1. /* 
  2. Requirements: Make the Closing Function of Forms Implemented 
  3.       Let the button also have the function of quitting the program 
  4. */  
  5.   
  6. import java.awt.*;  
  7. import java.awt.event.*;  
  8.   
  9. class  AwtEventDemo  
  10. {  
  11.     //Define references to components required for the graphical interface  
  12.     private Frame f=null;  
  13.     private Button but=null;  
  14.   
  15.     //Initial constructor  
  16.     AwtEventDemo()  
  17.     {  
  18.         init();  
  19.     }  
  20.   
  21.     //Form Creation and Function Implementation  
  22.     public void init()  
  23.     {  
  24.         //Instance component  
  25.         f=new Frame("my Frame");  
  26.         but=new Button("my Botton");  
  27.   
  28.         //Basic settings for windows  
  29.         //f.setSize(500,300); // Set Size  
  30.         //f.setLocation(300,200);//window initial display position  
  31.         f.setBounds(350,300,300,200);//Setting Form Size and Position Together  
  32.         f.setLayout(new FlowLayout());//Set to Streaming Layout  
  33.   
  34.         //Add the button component to the form  
  35.         f.add(but);  
  36.   
  37.         //Load events on forms  
  38.         myEvent();  
  39.   
  40.         //Display Form  
  41.         f.setVisible(true);  
  42.   
  43.     }  
  44.   
  45.     //Registration event  
  46.     private void myEvent()  
  47.     {  
  48.         //Closing function of form  
  49.         f.addWindowListener(new WindowAdapter()  
  50.         {  
  51.             public void windowClosing(WindowEvent e)  
  52.             {  
  53.                 System.out.println("window closing");  
  54.                 System.exit(0);//Close window program  
  55.             }  
  56.         });  
  57.   
  58.         //Let the button have the function of quitting the program  
  59.         /* 
  60.         The button is the event source. 
  61.         So which listener to choose? 
  62.         You learn by closing the form example that you want to know which component has what particular listeners. 
  63.         You need to view the functionality of the component object. 
  64.          Refer to the description of button. The Discovery button supports a unique listening addAction Listener. 
  65.          */  
  66.         but.addActionListener(new ActionListener()  
  67.         {  
  68.             public void actionPerformed(ActionEvent e)  
  69.             {  
  70.                 System.out.println("Button Control Window Closed");  
  71.                 System.exit(0);//Close window program  
  72.             }  
  73.         });  
  74.     }  
  75.   
  76.     public static void main(String[] args)   
  77.     {  
  78.         //Running Form Program  
  79.         new AwtEventDemo();  
  80.     }  
  81. }  

Practice:

  1. /* 
  2. Common Events: Keyboard Events and Mouse Events 
  3.  
  4. Requirement: List the contents of the specified directory in the form 
  5. */  
  6. import java.awt.*;  
  7. import java.awt.event.*;  
  8. import java.io.*;  
  9.   
  10. class KeyAndMouseEvent   
  11. {  
  12.     //GLOBAL VARIABLES INTERFACE COMPONENT REFERENCE  
  13.     private Frame f;  
  14.     private Button but;  
  15.     private TextField tf;  
  16.     private TextArea ta;  
  17.   
  18.     //Constructor  
  19.     KeyAndMouseEvent()  
  20.     {  
  21.         init();  
  22.     }  
  23.   
  24.     //Form Creation and Function Implementation  
  25.     public void init()  
  26.     {  
  27.         //Component instantiation  
  28.         f=new Frame("my fame");  
  29.         but=new Button("Jump");  
  30.         tf=new TextField(50);  
  31.         ta=new TextArea(30,58);  
  32.   
  33.         //Basic Form Settings  
  34.         f.setBounds(300,150,500,500);  
  35.         f.setLayout(new FlowLayout());  
  36.   
  37.         //add component  
  38.         f.add(tf);  
  39.         f.add(but);  
  40.         f.add(ta);  
  41.   
  42.         //Form Events  
  43.         myEvent();  
  44.           
  45.         //Form display  
  46.         f.setVisible(true);  
  47.     }  
  48.   
  49.     //Registration event  
  50.     public void myEvent()  
  51.     {  
  52.         //Form Closing Function  
  53.         f.addWindowListener(new WindowAdapter()  
  54.         {  
  55.             public void windowClosing(WindowEvent e)  
  56.             {  
  57.                 System.exit(0);  
  58.             }  
  59.         });  
  60.   
  61.         /* 
  62.         //Mouse Activity Event 
  63.         but.addActionListener(new ActionListener() 
  64.         { 
  65.             public void actionPerformed(ActionEvent e) 
  66.             { 
  67.                 System.out.println("The button is moving. 
  68.             } 
  69.         }); 
  70.         */  
  71.   
  72.         //Mouse event  
  73.         but.addMouseListener(new MouseAdapter()  
  74.         {  
  75.             //int count=0;  
  76.             public void mouseClicked(MouseEvent e)  
  77.             {  
  78.             //  if(e.getClickCount()==2)  
  79.             //System.out.println("double-click mouse button");  
  80.   
  81.             //System.out.println("mouse click button");  
  82.                 //System.exit(0);  
  83.   
  84.                 showFile();//Display in text area  
  85.             }  
  86.             /* 
  87.             public void mouseEntered(MouseEvent e) 
  88.             { 
  89.                 System.out.println("Mouse into the button range "+(+++ count) +" times "; 
  90.             } 
  91.             */  
  92.         });  
  93.   
  94.         /* 
  95.         //Button Keyboard Event 
  96.         but.addKeyListener(new KeyAdapter() 
  97.         { 
  98.             public void keyPressed(KeyEvent e) 
  99.             { 
  100.                 //Capture and press ctrl+entry at the same time 
  101.                 if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER) 
  102.                     System.out.println("Ctrl+Enter.....is Down"); 
  103.                  
  104.                 //System.out.println(e.getKeyText(e.getKeyCode())+"---"+e.getKeyCode());     
  105.             } 
  106.         }); 
  107.         */  
  108.   
  109.         //Textbox Keyboard Events  
  110.         tf.addKeyListener(new KeyAdapter()  
  111.         {  
  112.             public void keyPressed(KeyEvent e)  
  113.             {  
  114.                 /* 
  115.                 //Determine whether the input character is a number? 
  116.                 if(e.getKeyCode()<KeyEvent.VK_0||e.getKeyCode()>KeyEvent.VK_9) 
  117.                 { 
  118.                     System.out.println("The number you entered is illegal. Please multiply it. 
  119.                     e.consume();//Characters that do not display input 
  120.                 } 
  121.                 */  
  122.   
  123.                 if(e.getKeyCode()==KeyEvent.VK_ENTER)  
  124.                     showFile();//Display the contents of the directory into the text area  
  125.             }  
  126.         });  
  127.     }  
  128.   
  129.     //List directories or files under paths  
  130.     private void showFile()  
  131.     {  
  132.         String path=tf.getText();//Get text box content  
  133.         File file=new File(path);//Encapsulating paths as file objects  
  134.         //Judging whether it exists  
  135.         if(file.exists())  
  136.         {  
  137.             ta.setText("");//Empty the content in the text area  
  138.             //If it is a directory  
  139.             if(file.isDirectory())  
  140.             {  
  141.                 String[] dir=file.list();//List the files and directories under the directory  
  142.                 //ergodic  
  143.                 for (String name : dir)  
  144.                 {  
  145.                     ta.append(name+"\r\n");//Add to the text area  
  146.                 }  
  147.             }  
  148.             else  
  149.                 ta.append(file.getName());//If it is a file, only the name of the file is displayed.  
  150.         }  
  151.         else  
  152.             System.out.println("The path you entered does not exist. Please retransmit or go to the hospital.");  
  153.     }  
  154.       
  155.   
  156.     public static void main(String[] args)   
  157.     {  
  158.         //Run form  
  159.         new KeyAndMouseEvent();  
  160.     }  
  161. }  

 

Lecture 2: Application

Dialog

When a dialog box needs to be generated: This object needs to be created when it is invoked. For example, when misoperation occurs, a dialog box prompting error information is needed to create the object at this time.

Example:

Enhanced functionality for listing examples of specified directory content.

  1. /* 
  2. List the contents in the specified directory, and give an error message when the input path is incorrect. 
  3. */  
  4.   
  5. import java.io.*;  
  6. import java.awt.*;  
  7. import java.awt.event.*;  
  8.   
  9. class MyWindowDemo   
  10. {  
  11.     //Define required component references  
  12.     private Frame f;  
  13.     private Button but,bok;  
  14.     private TextField tf;  
  15.     private TextArea ta;  
  16.     private Dialog d;  
  17.     private Label lab;  
  18.   
  19.     //Constructor  
  20.     MyWindowDemo()  
  21.     {  
  22.         init();  
  23.     }  
  24.   
  25.     //Forms are basically set to function implementation  
  26.     public void init()  
  27.     {  
  28.         //Component instantiation  
  29.         f=new Frame("My Window");  
  30.         but=new Button("Jump");  
  31.         tf=new TextField(50);  
  32.         ta=new TextArea(30,60);  
  33.   
  34.         //Basic setup  
  35.         f.setBounds(300,150,500,500);  
  36.         f.setLayout(new FlowLayout());  
  37.   
  38.         //add component  
  39.         f.add(tf);  
  40.         f.add(but);  
  41.         f.add(ta);  
  42.   
  43.         //Form Events  
  44.         myEvent();  
  45.   
  46.         //Form display  
  47.         f.setVisible(true);  
  48.     }  
  49.   
  50.     //Registration event  
  51.     public void myEvent()  
  52.     {  
  53.         //Form Closing Function  
  54.         f.addWindowListener(new WindowAdapter()  
  55.         {  
  56.             public void windowClosing(WindowEvent e)  
  57.             {  
  58.                 System.exit(0);  
  59.             }  
  60.         });  
  61.   
  62.         //"Jump" Button Event  
  63.         but.addActionListener(new ActionListener()  
  64.         {  
  65.             public void actionPerformed(ActionEvent e)  
  66.             {  
  67.                 showFile();//List the contents of the directory in the text area  
  68.             }  
  69.         });  
  70.   
  71.           
  72.   
  73.         //Textbox Keyboard Events  
  74.         tf.addKeyListener(new KeyAdapter()  
  75.         {  
  76.             public void keyPressed(KeyEvent e)  
  77.             {  
  78.                 //If the keyboard presses the Enter key, the contents of the directory are displayed in the text area.  
  79.                 if(e.getKeyCode()==KeyEvent.VK_ENTER)  
  80.                     showFile();  
  81.             }  
  82.         });  
  83.     }  
  84.   
  85.     //Method of Content Display in Text Area  
  86.         private void showFile()  
  87.         {  
  88.             String path=tf.getText();//Get the path of the input  
  89.             File dir=new File(path);//Encapsulating paths into objects  
  90.             //Determine whether the input path exists and whether it is a folder?  
  91.             if (dir.exists()&&dir.isDirectory())  
  92.             {  
  93.                 ta.setText("");//Empty the content in the text area - ------------------------------------------------------------------------------------------------------  
  94.                   
  95.                 String names[]=dir.list();//List the contents of the directory  
  96.                 //ergodic  
  97.                 for (String name : names )  
  98.                 {  
  99.                     ta.append(name+"\r\n");//Add to text area  
  100.                 }  
  101.             }  
  102.             else  
  103.             {  
  104.                 //Dialog Basic Settings  
  105.                 d=new Dialog(f,"Error prompt",true);  
  106.                 d.setBounds(400,200,280,150);  
  107.                 d.setLayout(new FlowLayout());  
  108.   
  109.                 bok=new Button("Determine");  
  110.                 lab=new Label();  
  111.   
  112.                 //Add buttons and text  
  113.                 d.add(bok);  
  114.                 d.add(lab);  
  115.   
  116.   
  117.                 //Dialog box closes event  
  118.                 d.addWindowListener(new WindowAdapter()  
  119.                 {  
  120.                     public void windowClosing(WindowEvent e)  
  121.                     {  
  122.                         d.setVisible(false);//Exit dialog box  
  123.                     }  
  124.                 });  
  125.   
  126.                 //OK button event  
  127.                 bok.addActionListener(new ActionListener()  
  128.                 {  
  129.                     public void actionPerformed(ActionEvent e)  
  130.                     {  
  131.                         d.setVisible(false);//Press the confirmation key to exit the dialog box  
  132.                     }  
  133.                 });  
  134.   
  135.   
  136.                 String info="The path you entered:"+path+"It's wrong. Please try again!";  
  137.   
  138.                 lab.setText(info);//Setting label text content  
  139.                 d.setVisible(true);//display a dialog box  
  140.             }  
  141.         }  
  142.   
  143.     public static void main(String[] args)   
  144.     {  
  145.         //Run form  
  146.         new MyWindowDemo();  
  147.     }  
  148. }  


Menu: Menu

1. Menu Inheritance

       

2, explain

Menu: Menu, inherit MenuItem; there are icons in the right triangle, Menu and MenuItem can be added.

2) MenuBar: Menu bar, you can add menus and menu items. Generally, first create the menu bar, then create the menu.

Menu Item: Menu item, also known as menu item, has no right triangle icon and is the final menu item.

4) Menu event processing is the same as component, adding activity listener to event source of type MenuItem and Menu, and processing related events.

5) Add the menu to the Frame through the setMenuBar() method.

Example:

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3.   
  4. class MyMenuDemo   
  5. {  
  6.     //Define component references  
  7.     private Frame f;  
  8.     private MenuBar mb;  
  9.     private Menu m,subMenu;  
  10.     private MenuItem closeItem,subItem;  
  11.     //Constructor  
  12.     MyMenuDemo()  
  13.     {  
  14.         init();  
  15.     }  
  16. //Form Setting and Function Realization  
  17.     public void init()  
  18.     {  
  19.         //Form settings  
  20. f = new Frame("my window");  
  21.         f.setBounds(300,100,500,600);  
  22.         f.setLayout(new FlowLayout());  
  23.       
  24.         mb = new MenuBar();//Create menu bar  
  25.         m = new Menu("file");//create menu  
  26.         subMenu = new Menu("Submenu");//Submenu under menu  
  27.   
  28.         subItem = new MenuItem("subentry");//Submenu contains menu items  
  29.         closeItem = new MenuItem("Sign out");//Menu contains entries  
  30.           
  31. //Menu Add Menu Components  
  32.         subMenu.add(subItem);  
  33.         m.add(subMenu);  
  34.         m.add(closeItem);  
  35.         mb.add(m);  
  36.         //Form Add Menu Component  
  37.         f.setMenuBar(mb);  
  38.         //Events on Forms  
  39.         myEvent();  
  40.         //Form display  
  41.         f.setVisible(true);  
  42.     }  
  43.     private void myEvent()  
  44.     {  
  45.         //Close menu with close events  
  46.         closeItem.addActionListener(new ActionListener()  
  47.         {  
  48.             public void actionPerformed(ActionEvent e)  
  49.             {  
  50.                 System.exit(0);  
  51.             }  
  52.         });  
  53.         //Form Closing Function  
  54.         f.addWindowListener(new WindowAdapter()  
  55.         {  
  56.             public void windowClosing(WindowEvent e)  
  57.             {  
  58.                 System.exit(0);   
  59.             }  
  60.         });  
  61.     }  
  62.       
  63.     public static void main(String[] args)   
  64.     {  
  65.         new MyMenuDemo();  
  66.     }  
  67. }  

 

3. Double-click execution of jar package

Since it is a graphical interface, you need to run the program in the form of a graphical interface, not on the Dos command line, so how to execute the program by double-clicking the program? This requires packing the class file of the program.

The steps are as follows:

1. First, import a package in a java file, and then create a package if not, such as package mymenu.

2. Generating packages: By compiling Java c-d:myclass MyMenu.java, all. class files are generated under the MyClass folder on the C disk.

3. Create a new file in this directory, such as 1.txt or any other file with any extension, and then edit it in a fixed format: "Main-Class: mymenu.MenuDemo", which only writes the contents in quotation marks. You need to have a space after the colon and return to the car at the end of the file.

Compile: jar-cvfm my.jar 1.txt mymenu. If you want to add other information, you can compile jar directly and get the corresponding command.

5. Double-click at this time to execute.

Explain:

1) In a fixed format:

(a) If there are no spaces: IO exceptions are reported at compilation time, indicating invalid header fields. This shows that 1.txt is read by IO stream.

b. If there is no carriage return, the information of loading the main class will not be added to the list. MF, that is to say, the name of the main class of the attribute of the configuration list will not be loaded into the list, and it will not be executed.

2) The jar file must be registered in the system before it can run. The registration method is as follows:

A. For XP systems:

Open any dialog box, click the Tool button in the menu bar, and select the folder option

b. Select the new - > extension, set the extension to jar, and confirm

c. Select Advanced, change the icon, and then click New, named open.

d. In executable applications, click browse, add the entire file path of bin under jdk, and add - jar after the path.

For win7 system:

a. Change the way you open it: Right-click the.jar file, click the way you open it, and select the javaw.exe application in bin under jdk as the default program.

b. Modify the registry of the associated program: Open the registry (win+r), find the registry path HKEY_CLASSES_ROOT Aplications javaw.exe shell open command, right-click the string value, and add-jar to the original path, such as: Program Files Java j6 bin javaw.exe - jar "%1". Note that there should be spaces on both sides of the jar. Save.

c. Double-click to execute the jar program, and if it still can't execute, download the latest version of jdk.

Example:

  1. /* 
  2. Exercise: Complete a simple notebook program with Menu components. 
  3. Requirements: File menu, file opening, saving and exiting functions. Change the written program to double-click executable program. 
  4. */  
  5.   
  6. package mymenu;  
  7. import java.awt.*;  
  8. import java.awt.event.*;  
  9. import java.io.*;  
  10.   
  11. class MyMenuText  
  12. {  
  13.     //Define component references  
  14.     private Frame f;  
  15.     private TextArea ta;  
  16.     private MenuBar mb;  
  17.     private Menu fileMe;  
  18.     private MenuItem openMi,saveMi,otherSaveMi,closeMi;  
  19.   
  20.     private FileDialog openDia,saveDia;  
  21.   
  22.     private File file;  
  23.   
  24.     //Constructor  
  25.     MyMenuText()  
  26.     {  
  27.         init();  
  28.     }  
  29.   
  30.     //Function realization  
  31.     private void init()  
  32.     {  
  33.         //Component instantiation  
  34.         f=new Frame("MyText");  
  35.         ta=new TextArea();  
  36.           
  37.         mb=new MenuBar();  
  38.         fileMe=new Menu("file");  
  39.         openMi=new MenuItem("open");  
  40.         saveMi=new MenuItem("Preservation");  
  41.         otherSaveMi=new MenuItem("Save as");  
  42.         closeMi=new MenuItem("Sign out");  
  43.   
  44.         openDia=new FileDialog(f,"Select the open file",FileDialog.LOAD);  
  45.         saveDia=new FileDialog(f,"Where to save",FileDialog.SAVE);  
  46.   
  47.         //Basic setup  
  48.         f.setBounds(300,150,600,500);  
  49.   
  50.         //add component  
  51.         f.add(ta);  
  52.         f.setMenuBar(mb);  
  53.   
  54.         mb.add(fileMe);  
  55.         fileMe.add(openMi);  
  56.         fileMe.add(saveMi);  
  57.         fileMe.add(otherSaveMi);  
  58.         fileMe.add(closeMi);  
  59.   
  60.         //Events in Forms  
  61.         myEvent();  
  62.   
  63.         //Form display  
  64.         f.setVisible(true);  
  65.     }  
  66.   
  67.     private void myEvent()  
  68.     {  
  69.         //Form Closing Function  
  70.         f.addWindowListener(new WindowAdapter()  
  71.         {  
  72.             public void windowClosing(WindowEvent e)  
  73.             {  
  74.                 System.exit(0);  
  75.             }  
  76.         });  
  77.   
  78.         //Open event  
  79.         openMi.addActionListener(new ActionListener()  
  80.         {  
  81.             public void actionPerformed(ActionEvent e)  
  82.             {  
  83.                 //Display File Dialogue Window  
  84.                 openDia.setVisible(true);//------------------  
  85.                 String dir=openDia.getDirectory();//Get directory  
  86.                 String fileName=openDia.getFile();//Get the filename  
  87.                   
  88.                 if(dir==null||fileName==null)//Processing for opening a file dialog box but not doing anything  
  89.                     return;  
  90.           
  91.                 file=new File(dir,fileName);//File object  
  92.                 try  
  93.                 {  
  94.                     ta.setText("");//Every time a file is opened, the contents of the text area are emptied  
  95.                     //Read stream with buffer technology  
  96.                     BufferedReader br=new BufferedReader(new FileReader(file));  
  97.                     String line=null;//Read a row  
  98.                     while ((line=br.readLine())!=null)  
  99.                     {  
  100.                         //Add to text area  
  101.                         ta.append(line+"\r\n");  
  102.                     }  
  103.                     br.close();//Shut off flow  
  104.                 }  
  105.                 catch (IOException ie)  
  106.                 {  
  107.                     throw new RuntimeException("Failed to open file");  
  108.                 }  
  109.             }  
  110.         });  
  111.   
  112.         //Save events  
  113.         saveMi.addActionListener(new ActionListener()  
  114.         {  
  115.             public void actionPerformed(ActionEvent e)  
  116.             {  
  117.                 //If it is saved for the first time, the file dialog box is displayed  
  118.                 if(file==null)//-------------  
  119.                 {  
  120.                     //Display File Dialog Box  
  121.                     saveDia.setVisible(true);//----------------------  
  122.                     String dir=saveDia.getDirectory();  
  123.                     String filename=saveDia.getFile();  
  124.                       
  125.                     if(dir==null||filename==null)//--------------------  
  126.                         return;  
  127.   
  128.                     file=new File(dir,filename);  
  129.                       
  130.                 }  
  131.                 save();//Method of saving files  
  132.             }  
  133.         });  
  134.           
  135.         //Save as an event  
  136.         otherSaveMi.addActionListener(new ActionListener()  
  137.         {  
  138.             public void actionPerformed(ActionEvent e)  
  139.             {  
  140.                 //Does the file dialog display whether it is saved for the first time or not?  
  141.                 saveDia.setVisible(true);//----------------------  
  142.                 String dir=saveDia.getDirectory();  
  143.                 String filename=saveDia.getFile();  
  144.   
  145.                 if(dir==null||filename==null)//--------------------  
  146.                     return;  
  147.   
  148.                 file=new File(dir,filename);  
  149.   
  150.                 save();//Method of saving files  
  151.                 //When saved, the default file dialog box location is where the file is opened  
  152.                 openDia.setFile(file.getName());  
  153.             }  
  154.         });  
  155.   
  156.         //Exit event  
  157.         closeMi.addActionListener(new ActionListener()  
  158.         {  
  159.             public void actionPerformed(ActionEvent e)  
  160.             {  
  161.                 System.exit(0);  
  162.             }  
  163.         });  
  164.     }  
  165.       
  166.     //Save file  
  167.     private void save()  
  168.     {             
  169.         try  
  170.         {  
  171.             //Write stream with buffer  
  172.             BufferedWriter bw=new BufferedWriter(new FileWriter(file));  
  173.             //Get the content in the text area  
  174.             String text=ta.getText();  
  175.             bw.write(text);//Write to a file  
  176.             bw.close();//Shut off flow  
  177.   
  178.         }  
  179.         catch (IOException ie)  
  180.         {  
  181.             throw new RuntimeException("File save failed");  
  182.         }  
  183.     }  
  184.   
  185.     public static void main(String[] args)   
  186.     {  
  187.         //Program operation  
  188.         new MyMenuText();  
  189.     }  
  190. }  

Posted by aayatoos on Thu, 18 Apr 2019 18:36:35 -0700