Java Graphical Interface notes (1)

Source: Internet
Author: User
Tags line editor

Directory

JFrame form ..... ..... ..... ..... ....... .................. ..... ..... ..... ..... ..... .............. .......... 1

* Method Color

* Bar Color

* Attract attention

I.. JFrame form

  • Create a form
    When developing Java applications, you typically create windows with JFrame. Windows created with JFrame contain a title, Minimize button, maximize button, and Close button

    When creating a window with JFrame, you need to set the action to be performed when you click the Close button , set the method to pass the SetDefault closeoperation (int operation) method of the JFrame object. The method's entry parameters can be selected from the static constants of the JFrame class, with optional static constants (below the code)

     Public classTest () { Public Static voidMain (string[] args) {JFrame frame=NewJFrame ("New Window"); Create a new form, the title of the form is the content in "", JPanel panel=NewJPanel (); Jpanel is a panel container class, contained in swing; JTextArea TextArea=NewJTextArea (); JTextArea text area, JTextField text box panel.setlayout (NewGridLayout ()); layout is layouts; GridLayout Grid layout Textarea.settext ("Test"); //generate scroll bars when content in textarea is too longPanel.add (NewJScrollPane (TextArea));                       Frame.add (panel); Add a panel to the newly created form; Frame.setsize (200,200); Set the size of the form frame.setvisible (true); Note that this step must be finally called, making this form visible, false is not seen;
    Frame.setdefaultcloseoperation (frame. Exit_on_close); Defines the action of clicking the Close button;}}

    setdefaultcloseoperation (int operation): sets the action that the user performs by default when "Close" is initiated on this form. The parameters in the method are explained as follows:

    For "0" or Do_nothing_on_close:

    (defined in windowconstants): do nothing; ask the program to handle the operation in the Windowclosing method of the registered WindowListener object.

    For example, change the instance program code to F.setdefaultcloseoperation (f. do_nothing_on_close), or f.setdefaultcloseoperation (0), and then look at the effect, You can see that the window cannot be closed, the following is the same test method, no longer explained.

    For "1" or hide_on_close

    The form is automatically hidden after any registered WindowListener object is called. The program is not closed at this time, only the program interface is hidden. You can open Task Manager, you can see a process called "Java.exe" (if debugging runs multiple Java programs, you will see more than one "java.exe" process), if you use EditPlus test program, you will find that when you click the window's Close button to close the window, It is not possible to debug the program again because the program thread is not closed, and the Java.exe (if there are multiple "java.exe" processes, which are closed first, and then tested for the problem), will not be able to recompile the program until it is shut down in Task Manager.

    For "2" or dispose_on_close

    Automatically hides and releases the form after calling any registered WindowListener object. However, you continue to run the application, freeing up the resources used in the form.

    For "3" exit_on_close (defined in JFrame): Exits the application using the System exit method. Used only in the application. End the application.

    By default, this value is set to Hide_on_close.

    When commenting out the F.setdefaultcloseoperation (F.exit_on_close) in the instance, the effect and the F.setdefaultcloseoperation (f. Hide_on_close) When the statement is played; or f.setdefaultcloseoperation (1);


  • JFrame The default display location of the windowTo start drawing from the (0,0) point, draw from the upper-left corner of the display. Usually more desirable to display in the center of the display, you can pass the static method of the Toolkit classGetdefaulttoolkit ()Gets an object of the Toolkit class, and then passes the Toolkit object'sgetscreensize ()method to obtain an object of the dimension class, the size of the display can be obtained by dimension objects, such as the width and height of the display, and the typical code for the dimension object is as follows:
    Dimension displaysize = Toolkit.getdefaulttoolkit (). Getscreensize ();
    The GetSize () method of the JFrame object can also be used to get an object of the dimension class, through which the dimension object can get the size of the JFrame window, such as the width and height of the JFrame window, and the typical code for the dimension object is as follows:
    Dimension framesize = Frame.getsize ();
    Using the above two objects of the dimension class, you can calculate the starting point of the display in the center of the display, and then through the JFrame object's setlocation (int x, int y) method, set the JFrame window in the display of the beginning of the drawing point, The typical code is as follows:
    frame.setlocation((displaysize.width-framesize.width)/2, (Displaysize.height-framesize.height)/2);
    Windows created with JFrame are not visible by default, that is, when the window is not drawn on the monitor at run time, the method that is set to be visible is through the setvisible (Boolean B) method of the JFrame object, and the entry parameter is set to True, the typical code is as follows:
    frame.setvisible (true):
  • Modify Icon  

    Seticonimage(Toolkit. Getdefaulttoolkit (). CreateImage (
GetClass ().     GetResource ("Login.png")); (Note: The picture login.png to be placed in the same folder as the class that called the picture; and Java does not seem to support ICO format)
    • How Java swing refreshes jtextarea in real time to show what append just added

After executing textarea.append ("message") in the code, if you want the update to appear immediately on the interface instead of when the main thread of swing returns, we will typically call Textarea.invalidate () after the statement. and Textarea.repaint ().

The problem is that this method does not have any effect, the content of textarea no change, this may be a swing bug, there is a clumsy way to achieve this effect, is to execute the following statement

Textarea.paintimmediately (Textarea.getbounds ());

Or
Textarea.paintimmediately (Textarea.getx (), Textarea.gety (), Textarea.getwidth (), Textarea.getheight ());

At this point, you will find that the information you have just added has been displayed in real time.

  • paint and add mouse events
    FinalImage img = Toolkit.getdefaulttoolkit (). GetImage (Test.class. GetResource ("Map.png")); JTextArea Ta=NewJTextArea () {//text area;{Setopaque (false);//set opaque parameters, missing when background picture is not displayed            }             Public voidPaint (Graphics g) {G.drawimage (IMG,0, 0, This); Super. Paint (g);        }        }; MouseListener ml=NewMouseListener () {//mouse Listener;             Public voidmouseclicked (MouseEvent e) {//MouseEvent is the type of mouse activity,                if(E.getclickcount () = = 2) {//GetClickCount () The number of mouse clicks statistics;System.out.println ("Mouse double clicked"); }                        }                       Public voidmouseentered (MouseEvent e) {//TODO auto-generated Method Stub            }             Public voidmouseexited (MouseEvent e) {//TODO auto-generated Method Stub            }             Public voidmousepressed (MouseEvent e) {//TODO auto-generated Method Stub            }             Public voidmousereleased (MouseEvent e) {//TODO auto-generated Method Stub            }               };        Ta.addmouselistener (ML); Ta.setbounds (0, 0, 300, 200); Ta.seteditable (false);

  • Write the content in one textarea, the other two display simultaneously
    /*JTextArea is a multi-line editor, JTextField is a simple single-row text editor that is derived from the JTextComponent class, so they contain common methods, such as setting and getting the displayed text, specifying whether the text is editable, Or whether it is read-only, manages the cursor position within the text, and manages text selection. The model of a text component is an object called document, and for a jtextarea or jtextfield, adding or removing text for it changes the corresponding document. When some kind of change occurs, the text-related events are generated by the document itself, not by the visual component. Therefore, in order to receive notification of JTextArea modification, it is necessary to register with the underlying document instead of the JTextArea component itself:*/JTextArea TextArea=NewJTextArea ();D ocument D=textarea.getdocument ();d. Adddocumentlistener (Somelistener);/*as an example, what you type in any of the text areas will be reflected in all three areas. All we have to do is let all the text areas share a data model. */ImportJava.awt.Container;Importjava.awt.GridLayout;ImportJavax.swing.JFrame;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTextArea; Public classSharemodel { Public Static voidMain (string[] args) {JFrame frame=NewJFrame ("Sharemodel"); JTextArea Areafiftyone=NewJTextArea (); JTextArea Areafiftytwo=NewJTextArea ();        Areafiftytwo.setdocument (Areafiftyone.getdocument ()); JTextArea Areafiftythree=NewJTextArea ();               Areafiftythree.setdocument (Areafiftyone.getdocument ()); Container content=Frame.getcontentpane (); Get all AWT components of jframe in one container; This can be used to import into other containers to achieve an identical interface; Content.setlayout (NewGridLayout (3,1)); Create a grid layout with the form format you just acquired; Content.add (NewJScrollPane (Areafiftyone)); Content.add (NewJScrollPane (areafiftytwo)); Content.add (NewJScrollPane (Areafiftythree));        Frame.setdefaultcloseoperation (Jframe.exit_on_close); Frame.setsize (300,300); Frame.setvisible (true); }}/*when you type in a text area, this text area will accept keyboard events that will invoke methods in the document to update the data, and the document will send events to other text areas, notifying that an update has occurred so that they can correctly display the new data for the document. But all of this doesn't need our attention. All you have to do is notify the text area to use the same data. Swing will take over the rest. Also need to note, JTextArea no scrolling function, beyond the text area of the content can not be displayed, drag with the mouse can not be seen. But it implements the swing scrollable interface. It must be placed inside the JScrollPane to enable scrolling. */

  • JFrame other methods;
    Common Methodsprotected voidAddimpl (Component comp, Object constraints,intindex) To add the specified child Component. protectedJRootPane Createrootpane () is called by the constructor method to create the default RootPane. protected voidFrameinit () is called by the constructor method to initialize the JFrame appropriately. AccessibleContext Getaccessiblecontext () gets the accessiblecontext associated with this JFrame. Container Getcontentpane () returns the ContentPane object for this formintgetdefaultcloseoperation () returns the user initiated on this form"Close"when the operation is performed. Component Getglasspane () returns the GlassPane object for this form. Graphics Getgraphics () creates a graphics context for the component. JMenuBar Getjmenubar () returns the menu bar set on this form. JLayeredPane Getlayeredpane () returns the Layeredpane object for this form. JRootPane Getrootpane () returns the RootPane object for this form. Transferhandler Gettransferhandler () Gets the Transferhandler property. Static Booleanisdefaultlookandfeeldecorated () if the newly created JFrame should provide a Window decoration for the current appearance, returntrue. protected Booleanisrootpanecheckingenabled () returns whether the call to add and setlayout is forwarded to ContentPane. protectedString paramstring () returns the string representation of this JFrame. protected voidprocesswindowevent (windowevent e) Handles window events that occur on this component. voidRemove (Component comp) removes the specified component from the container. voidRepaint (LongTimeintXintYintWidthintheight) redraws The specified rectangular area of this component within a time millisecond. voidSetcontentpane (Container contentpane) sets the ContentPane property. voidSetdefaultcloseoperation (intoperation) Set up users to initiate on this form"Close"action is performed by default. Static voidsetdefaultlookandfeeldecorated (Booleandefaultlookandfeeldecorated)
    Provides a hint about whether a newly created JFrame should have a window decoration (such as a border, a widget that closes a window, a caption, and so on) that the current appearance provides for it. voidSetglasspane (Component glasspane) sets the GlassPane property. voidSeticonimage Sets the image to display as the icon for this window. voidSetjmenubar (JMenuBar menubar) sets the menu bar for this form. voidSetlayeredpane (JLayeredPane layeredpane) sets the Layeredpane property. voidsetlayout (LayoutManager manager) settings LayoutManager. protected voidSetrootpane (JRootPane root) sets the RootPane property. protected voidsetrootpanecheckingenabled (Booleanenabled) Sets whether calls to add and setlayout are forwarded to ContentPane. voidSettransferhandler (Transferhandler newhandler) sets the Transferhandler property, which is a mechanism that supports the transfer of data to this component. voidUpdate (Graphics g) just calls paint (g).

Java Graphical Interface notes (1)

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.