Dark Horse programmer-java GUI use

Source: Internet
Author: User
Tags event listener save file

--java Training, Android training, iOS training,. NET training, look forward to communicating with you! ——

I. Overview

GUI (graphical user Interface, GUI), Java provides two packages for implementing a graphical user interface, namely Java. AWT and Javax.swing. Where AWT needs to invoke Local system implementation, which is a heavyweight control, there are some differences in the interface display in different systems because it relies mainly on the interface provided by the system. To improve cross-platform, swing built a graphical interface system based on AWT, which provides more components and is fully implemented in Java, which enhances the portability of programs and belongs to lightweight controls. It is not limited to AWT, but also adds a lot of expanded controls.

Second, the layout

Component emissions in containers, called layouts, have layout controls in the following different types of layouts in Java:

    • FlowLayout: Streaming layout. In order from left to right, the Panel default layout manager.
    • BorderLayout: Boundary layout manager, East, west, south, north, middle, Frame default layout manager.
    • GridLayout: Grid layout manager, matrix arrangement for rules.
    • CardLayout: Card Layout manager, tab form.
    • GridBagLayout: A non-regular matrix.
Third, the window

FrameYou can create a form that you typically create by following these steps:

    1. Create a frame form.
    2. Basic settings for the form (such as size, position, layout, and so on).
    3. Define the component.
    4. Adds a component to the form's interior through the form's Add method.
    5. Let the form appear, by setVisible(true) displaying it.

Simply create a graphical window with the sample code as follows:

Importjava.awt.*;ImportJava.awt.event.*;class Myadapter extends Windowadapter { Public void windowclosing(WindowEvent e) {System.exit (0); } Public void windowactivated(WindowEvent e) {System.out.println ("Activate"); } Public void windowopened(WindowEvent e) {System.out.println ("Open"); }}class Demo { Public Static void Main(string[] args) {Frame frame =NewFrame ("Hi");//title of the form        //Specify wide heightFrame.setsize ( -, -);//Specify the position of the window on the screenFrame.setlocation ( -, $);//Set layoutFrame.setlayout (NewFlowLayout ());//Add a buttonButton Button =NewButton ("OK");        Frame.add (button); Frame.addwindowlistener (NewMyadapter ());//Display windowFrame.setvisible (true); }}

The graphical interface that runs out is as follows:

Form Style
Iv. Events

The features of the event monitoring mechanism include the following components:

    • Event Source: The source of the triggering event, with different event sources triggering different event types, AWT or the graphical interface components in the swing package.
    • Event: Each event source has its own unique corresponding event and common events.
    • Listener: The action that can trigger an event (more than one action) is already encapsulated in the listener.
    • Event handling: (all three of which are already defined in Java) What we do is to complete each event's corresponding processing action.

Under the action of an external action, an event source is created, the event source is encapsulated into an object, the event object is passed to the event listener, and the event listener makes the corresponding action.

Event Monitoring Mechanism flowchart

Adding a Close event to the window can Frame be addWindowListener(WindowListener ) added by adding, but there is a series of methods in this interface, if adding this interface must implement all methods, now just click the Close button of the window, and then exit the window, so find another method. Java provides a class for WindowAdapter the abstract class, this class implements the WindowListener interface, just a few empty operations, then we only need to inherit this class, such as the following syntax:

Importjava.awt.*;ImportJava.awt.event.*;class Demo { Public Static void Main(string[] args) {Frame frame =NewFrame ("Hi");//title of the form        //Specify wide heightFrame.setsize ( -, -);//Specify the position of the window on the screenFrame.setlocation ( -, $);//Set layoutFrame.setlayout (NewFlowLayout ()); Frame.addwindowlistener (NewWindowadapter () { Public void windowclosing(WindowEvent e) {System.exit (0); }        });//Display windowFrame.setvisible (true); }}

Many times you will see some of the software's controls will be different depending on the position of the mouse to render different styles, such as when the mouse on top of the selected state and so on, then this need to add a mouse response to the event, the code is as follows:

Importjava.awt.*;ImportJava.awt.event.*;class Demo { Public Static void Main(string[] args) {Frame frame =NewFrame ("Hi");//title of the form        //Specify wide heightFrame.setsize ( -, -);//Specify the position of the window on the screenFrame.setlocation ( -, $);//Set layoutFrame.setlayout (NewFlowLayout ()); Frame.addwindowlistener (NewWindowadapter () { Public void windowclosing(WindowEvent e) {System.exit (0);        }        }); Button Button =NewButton ("Hello, everyone!" ");//button.setsize (a);Button.addmouselistener (NewMouseadapter () { Public void mouseentered(MouseEvent e) {Button.setlabel ("The mouse is coming in."); } Public void mouseexited(MouseEvent e) {Button.setlabel ("The mouse is out.");        }        }); Frame.add (button);//Display windowFrame.setvisible (true); }}

The following is a comprehensive example to illustrate the Java GUI programming, the instance content is through the system's file selection interface, select the specified file, and then the directory and file content display,

Importjava.io.*;Importjava.awt.*;ImportJava.awt.event.*;class Demo { Public Static void Main(string[] args) {NewDemo (); }//define interface components and member variables    PrivateFrame Mframe;PrivateTextField Minputbox;PrivateTextArea Moutputbox;PrivateButton Mchoose;PrivateFileDialog Mfiledialog, Msavedialog;PrivateMenuBar Mmenubar;PrivateMenu Mmenu;PrivateMenuItem Mchoosemenuitem, Msavemenuitem, Mexitmenuitem;PrivateFile Msavefile; Public Demo() {init ();    Initevents (); }/** * Initialize interface * /    Private void Init() {mframe =NewFrame ("file List Window"); Mframe.setbounds ( -, $, -, -); Mframe.setlayout (NewFlowLayout ()); Minputbox =NewTextField ( the); Moutputbox =NewTextArea ( -, the); Mchoose =NewButton ("Select Directory");        Mframe.add (Minputbox);        Mframe.add (Mchoose);        Mframe.add (Moutputbox); Mfiledialog =NewFileDialog (Mframe,"Select File", filedialog.load); Msavedialog =NewFileDialog (Mframe,"Save File", Filedialog.save);//Initialize menuMmenubar =NewMenuBar (); Mmenu =NewMenu ("File"); Mchoosemenuitem =NewMenuItem ("Open"); Msavemenuitem =NewMenuItem ("Save"); Mexitmenuitem =NewMenuItem ("Exit");        Mmenu.add (Mchoosemenuitem);        Mmenu.add (Msavemenuitem);        Mmenu.add (Mexitmenuitem);        Mmenubar.add (Mmenu);        Mframe.setmenubar (Mmenubar); Mframe.setvisible (true); }/** * Initializing component Events * /    Private void initevents() {//Add an Exit event for the windowMframe.addwindowlistener (NewWindowadapter () { Public void windowclosing(WindowEvent e) {System.exit (0); }        });//Select FileMchoose.addactionlistener (NewActionListener () { Public void actionperformed(ActionEvent e)            {Choosefile (); }        });//Menu Open FileMchoosemenuitem.addactionlistener (NewActionListener () { Public void actionperformed(ActionEvent e)            {Choosefile (); }        });//Save fileMsavemenuitem.addactionlistener (NewActionListener () { Public void actionperformed(ActionEvent e)            {SaveFile (); }        });//ExitMexitmenuitem.addactionlistener (NewActionListener () { Public void actionperformed(ActionEvent e) {System.exit (0);    }        }); }/** * Select file using FileDialog System interface * /    Private void Choosefile() {mfiledialog.setvisible (true);        String Dirpath = Mfiledialog.getdirectory (); String fileName = Mfiledialog.getfile ();if(Dirpath! =NULL|| FileName! =NULL) {File File =NewFile (Dirpath,filename);if(File.exists ())                {msavefile = file;            LoadFile (Msavefile); }        }    }/** * Save the file, if it is the first time select Save location * /    Private void SaveFile() {if(Msavefile = =NULL) {msavedialog.setvisible (true);            String Dirpath = Msavedialog.getdirectory (); String fileName = Msavedialog.getfile ();if(Dirpath! =NULL&& FileName! =NULL) {Msavefile =NewFile (Dirpath, fileName);            Savecontent (); }        }Else{savecontent (); }    }/** * Save the file and save the contents of the text box to the specified location * /    Private void savecontent() {BufferedWriter writer =NULL;Try{writer =NewBufferedWriter (NewFileWriter (Msavefile));            String content = Moutputbox.gettext ();        Writer.write (content); }Catch(IOException e) {        }finally{Try{if(Writer! =NULL) {writer.close (); }            }Catch(IOException e)        {}; }    }/** * Loading file contents * /    Private void LoadFile(File file) {if(File.exists ())            {Minputbox.settext (File.getabsolutepath ()); Moutputbox.settext (""); BufferedReader reader =NULL;Try{reader =NewBufferedReader (NewFileReader (file)); String line =NULL; while(line = Reader.readline ())! =NULL) {Moutputbox.append (line+"\ r \ n"); }            }Catch(IOException e) {            }finally{Try{if(Reader! =NULL) {reader.close (); }                }Catch(IOException e) {}            }        }    }}
Interface operation

Dark Horse programmer-java GUI use

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.