Java brief reminder

xiaoxiao2021-03-06  43

The layout of the component is in the container When we add the component to the container, you want to control the position in the container in the container. By default, there are layout managers in each container. If the default layout manager's default layout manager does not meet the user's needs, users can use other layout managers to replace it. The Java's Java.awt package defines five layout classes, and the instance of each layout class corresponds to a layout policy, which is: FlowLayout, BorderLayout, Cardlayout, Gridla yout and GridbagLayout. Where GridbagLayout is the most complex and powerful. 1. FlowLayout layout FlowLayout is the layout of the Panel container and the Applet type container. If you do not specify a layout specified for Panel and Applet, they use the FlowLayout layout. FlowLayout corresponds to the layout, follow the container of this layout to arrange the components from left to right, and then go to the next line after the row is full, and the components in each row are all arranged. Components in each row Come amazed. When the components are not available, it is very convenient to use this strategy, but when the component elements in the container are incremented, it is high and low. The previous example is used in this layout. For containers using FlowLayout, add components to use simple add (component name) commands, which are sequentially arranged in the container. Sometimes because F LowLayout has limited layout capacity, the program will use a container nested method. This nested container component can have its own components and their own layout, so that the layout of the entire container reaches the application. For a container that does not use a FlowLayout layout, if you need to change its layout policy to flowLayout, you can use the following statement: set layout (new flowLayout ()); setLayout () method is the method of all containers' parent class Container, with Set the layout for the container. FlowLayout class has three constructor: public FlowLayout () public FlowLayout (int alignment) public FlowLayout (int alignment, int horizontalGap, int verticalGap) alignment parameter must be FlowLayout.LEFT, FlowLayout.CENTER or FlowLayout .RIGGHT. Horizontalgap and VerticalGAP parameters specify the component interval distance (in pixels). If the user does not specify the interval value, FlowLayout will automatically specify its value of 5.2. BorderLayout layout BorderLayout is also a simple layout strategy, which simply divides space in the container into the East, West, South, North, and China. Region, each additional components should indicate which area is added to this component. BorderLayout can only specify 5 regional locations. If more than 5 components need to be added in the container, nesting or changed to other layout strategies must be used. (Components can be less than 5) When the user adds to the component to the container using the BorderLayout Layout Manager, the user must use the add () method of the two parameters, and the first parameter must be "north", "South", " EAST "," West "or" center ". If the user is invalid if the user uses a parameter or the specified first parameter is invalid, the component will not be displayed.

By default, BorderLayout will make it managed between components without a gap, and the user can specify a gap with the following construction method: Public BorderLayout (int horizontalgap, int verticAp) Example: E13, Example12_13, Cardlayout layout Using Cardlayout Layout Using Cardlayout container Hand up multiple components, but in fact, the container can only be displayed from these components, just like a stack of cards can only display the top one, this displayed component will occupy all containers. space. The general steps using CardLayout are as follows (assuming container is called CON): (1) Creating a CardLayout object as a layout. Such as: mycard = new cardlayout (); (2) Use the container's setLayout () method to set up the container settings. Such as: con.setLayout (MyCard); (3) Call the Add () method of the container to add the component to the container. Con. ADD (component code, component); component code is additional, and the name of the component is not necessarily related. (4) The created layout MyCard is provided with the show () method provided by the CardLayout class, which is more controlled by the container name Con and the component code code: mycard.show (CON, component code); or press the order of the container to display the order of the container Components, such as the first (con) method displays the first component in the CON, the last component in the CON, NEXT (CON) displays the next component, Previous (CO N) displays the previous components, etc. (The first addition of CON is the first one of the "card" style, sequentially sorted). Example: E144, GridLayout layout GridLayout is a more layout editor, its basic layout strategy is to divide the container into several rows of grid areas, and components are located in these divided grids. GridLayout is more flexible, how many grids are freely controlled by the program, and the component positioning is more accurate, using the GridLayout layout editor is as follows: Create a GridLayout object as the layout, specify the number of lines and columns of the divided grid, and use the container The setLayout () method sets this layout editor for the container: setLayout (New GridLayout (number of lines, number of columns)). The method of calling the container add () adds the component to the container. After the component is detached from left to right, then the second line is raised, and then push it. Each grid must be filled in components. If you want to look at a gap, you can add an empty tag for it: add (new label ()). Example: E15 (Example12_3) Since each grid in the GridLayout layout is the same size and the forced component is the same size as the grid, each component in the container is also the same size, which is very unnatural. To overcome this shortcomings, you can use the container nested.

Such as: A container uses a GridLayout layout, divides the container into three rows of mesh; then you can add another container to a grid, and the added container can be set to GridLayout layout, divide themselves into several grid. With this method, you can design a layout that meets a certain need. Example: E16 (Example12_4) 5, GridbagLayout layout GridbagLayout is the most flexible, most complex layout manager provided by AWT. GridbagLayout places the components in multiple rows, allowing the specified components to cross multi-line or more columns. If the user increases the applet window, the user finds that the last line will hold all the new vertical spaces, and all new horizontal direction will be divided by all columns. This change is based on the right of a single component in GridbagLayout in applet. Users will also see that each component will occupy as much space as possible, this action is also specified by applet. Temporary discussion. 6. NULL layout and setbounds method We can set the layout of a container to NULL layout (empty layout). SetBounds (int A, int b, int width, intang) method is a method that all components have, and component calls that the method can set the size of the own and in the container. Suppose P is a container: p.setlayout (null); set the layout of the P to an empty layout. Adding a component C to the container P to the empty layout requires two steps, first add components to the container using the add (c) method, then the component C will call the setbounds (int A, int b, int width, int hotht) method to set the component. The position of the container and the size of the itself. Components are all rectangular structures, parameters A, B are position coordinates in the upper left corner of the component C; Weidth, Height is the width and high of component C. Example: E17 (Example12_6) Basic rules using the layout manager: (1) User requires that all spaces are required to display components, consider using BorderLayout and GridbagLayout. If B OrderLayout is used, the user should place the components of the occupied space in the central part. If you use GridLayout, the user needs to set a restriction condition for the component. (2) When the user needs to display fewer components in a compact line, the user can consider the panel receiving component and use the default layout manager of the panel to FLO WLAYOUT. (3) The user needs to display some components of the same size in multiple lines or multiple columns, and GridLayout is best suited. If necessary, you can use the panel to accommodate components. The canvas diagram is a general component that does not have any functions or any events. It is a simple component that can be painted above, not a container. Class CANVAS in the java.awt package is responsible for creating a canvas object. Creating a common way to creating a canvas is a subclass of Canvas to create a canvas object and rewrite the method of the parent class in the subclass: Paint. It should be noted that it is necessary to give the size of the canvas (pixel) in the constructor of the category of the canvas.

Example: E18 (Example11_3) In the above example, the constructor in the MyCanvas class must get its size via the getSize () method, when using the getSize () method, the getPreferredSize () method in this class is automatically executed, In this method, the size of the canvas is given by using the DIMENSION class (in the Jav AWT package). Using the AWT component drawing using the Graphics class in the AWT component, except that you can display a string, you can draw in the application's frame window. A rich approach is defined in the Graphics class to draw a variety of graphics. Some methods that are commonly used are: 1. Display strings and character arrays DrawString (String S, INT X, INT Y); from the X and Y parameters Start the right to display the string to the right place. Drawchars (Char Data [], int offset, int layth, int x, int y); X and Y parameters specify the location of the display character, the OFFSET, and the Length parameter specify the characters to display in the array. Example: E19 (Example17_2) 2 Draw a straight line Drawline (int X1, int y1, int x2, int y2); 3, plotting rectangular DrawRect (int X, int y, int width, int Height); X and Y parameters designation The position, Width and Length parameters in the upper left corner specify the width and height of the rectangle. FillRect (int X, int y, int width, int Height); DrawRect method only draws rectangular contours, while the FillRect method draws a rectangular and fill it. DrawroundRect (int X, int y, int width, int hotht, int arcwidth, int arch); painted rectangles, ArcWidth and Archeight parameters specify the size of the rectangular rounded corners. When width = height = arcwidth = a rcheight is a ring. 4, draw an elliptical Drawoval (int X, int y, int width, INT Height); X and Y indicate the distance from the ellipse of the X-axis and the Y-axis, the unit is pixel; the parameter width, Height represents the width and high of the ellipse. When width = height is a ring. Filloval (int X, int y, int width, int Height); Filloval method uses the color of the color to color the color of the color. 5. Draw arc Drawarc (int X, int y, int width, int hotht, int starangle, int arch; statang and Arcangle represents the rounded angle of the arc start angle and arc corresponding to the arc. Fillarc (int X, int y, int width, int hotht, int starangle, int arch); Filloval method uses the color painted arc specified by the SetColor method.

Example: E20 E21 (Example12_2) Processing Select Box Event When the user turns the selection box from the unselected state to select the status or from the selected state to the unselected state, a selection box event occurs. For the event source of the selection box, it has an event, which is the change in the selection box. This event source obtains the monitor's method is AddItemlistene R (). Treating the interface of the event is itemListener, the method in the interface is ItemStateChanged (ItemEvent E). Select box The type of event is the ItemEvent type, that is, when you have never selected or from selected to unchecked, the class item ItemEvent in Java package java.awt.e Vent automatically creates an event object. There is an important way in the ItemEvent class: getItemSelectable (); it returns the event source that triggers the selected status change event. That is to say, for the ItemEvent event type event, if you want to find the event source, you need to use the GetItemSelectable () method. Example: E22 (Example13_4) E23 (Example13_3) Processing the drop-down list event pull-down list is actually a selection control. When a user selects an option in the selection control, an event on the selection control occurs. For the selection control, it has an event, which is the change in the selection of the control. This event source obtains the monitor's method is AddItemliste Ner (). The interface to which the event is ItemListener, the method in the interface is ItemStateChanged (ItemEven T e). Selecting the control This type of event is the itemEvent type, that is, when selecting options from the selection control, the class item ItemEvent in Java package java.awt.event automatically creates an event object. There is an important way in the ItemEvent class: getItemSelectable (); it returns the event source that triggers the selected status change event. That is to say, for the ItemEvent event type event, if you want to find the event source, you need to use the GetItemSelectable () method. Example: E24 (Example14_2) Handling List Event Swark List Event Source There are two events: One is the mouse double-click an option, and the other is that the mouse click an option. The method for obtaining a monitor for the first event event source is Add activityListener (). The interface to handle the event is an actionListener, the method in the interface is ActionPerfor Med (ActionEvent E). The type of this event is ActionEvent, that is, when you double-click an option from the list, the class a ctione at the java package java.awt.event automatically creates an event object. There is an important acquisition source method in the ActionEvent class: getSource (). The method for obtaining a monitor for the second event source is: additemlistener (). Treating the interface of the event is itemListener, the method in the interface is ItemStateChanged (ItemEvent E).

Selecting a control This event is the ItemEvent type, that is, when you click the option, the class IT EMEVEN in Java package java.awt.event automatically creates an event object. There is an important event source method in the ItemEvent class: GetItemSelectable (). It returns a source of the event that triggers the selected status change event. That is to say, for an event type of the ItemEvent event, you need to use the GetItemSelectable () method if you want to find the event source. Example: E25 (Example14_4) Window 1 Click an option with your mouse. The method of obtaining the monitor is: addActionListener (). The interface to handle the event is an actionListener, the method in the interface is ActionPerformed (ActionEvent E). The type of this event is ActionEvent, that is, when the menu item is clicked, the class ACTI onevent in Java package java.awt.event automatically creates an event object. There is an important way to get an event source in the ActionEvent class: getSource (). Example: E29 (EXAMPLE15_5) E30 (Example15_6) 4, add menu split lines and embedded submenu To add menu split lines, just use the addSeparetor () method in the MENU class. The menu item itself can also be a menu, such a menu item is called a submenu. Example: E31 (EXAMPLE15_9) Dialog 1 The default layout of the dialog is the BorderLayout layout. You must have a dialog size setting when the dialog is created. In its constructor, you must call the corresponding constructor of the parent class using the super () method. Example: E32 (Example16_1) In the above example, the created dialog is visible. But we want to set up buttons or menus in its dependencies, open or close the dialog box at any time via menu item or button event. In addition, we also hope that the dialog box can complete some tasks. Example: E33 (Example16_2) 2, File dialog FileDialog is a subclass of the Dialog class, which is called the file dialog. The File dialog is a dialog window that opens files and saves files. The file dialog must also be attached to a window object. The file dialog only provides an interface for a file operation. To actually implement the operation of the file, you must learn the input and output flow of the file. Example: E34 (Example16_3) Input Output Flow I / O stream provides a channel program that can be sent to the descending sequence in the source to the destination. Java's I / O stream provides a large number of streams (in the package java. IO).

All of them are subclasses of the INPUTSTREAM abstraction class, while all output rivers are subclasses of an OutputStream abstraction class. First, the FileInputStream class If the user's file read demand is relatively simple, the user can use the FileInputStream class, which is a simple input class that is generated from the InputStream. All methods of this class are inherited from the InputStream class. In order to create an object of the FILEINPUTSTREAM class, the user can call its constructor: fileInputStream (String name); // Parameter is file name fileInputStream (file file); // Parameter is file object 1. Read the file file input stream (subclass of the input stream) to provide access to the file using the file input stream. To read files, use the file input stream constructor to open a stream that reaches the file. For example, in order to read a file called myfile.dat, create a file input stream object is as follows: fileinputstream istream = new fileinputstream ("myfile.dat"); or file f = new file ("myfile.dat"); fileInputStream iStream = New fileInputStream (f); FILE class has two commonly used constructors: file (string s); // s determines the name of the file, and the file and application are in the same directory. File (String Directory, String S); // Directory determines the directory of the file, s determines the name of the file. 2. Processing I / O Experience When using the file input stream constructor, it may have an exception, and the Java generates an error signal, which uses an IOExce Piod (IO Exception) object to represent this error signal. The program must detect and process this exception using a Catch block. In order to associate a file input object with a file, use the code similar to the following: Try {fileInputstream INS = New fileInputStream ("myfile.dat");} catch (ioException e) {system.out.println "File Read Error:" E);} Since I / O operation is particularly sensitive to errors, many other stream constructors and methods also produce I / O abnormalities. It is also necessary to capture (CATCH) or process these exceptions in the same manner as shown in the above block. 3. The unique purpose of reading byte input streams from the input stream is to provide channels to the data, and the program can read data by this channel, the READ () method provides a basic method of reading data from the input stream. Int read (); // read () method reads a single byte of data from the input stream.

The method returns to the paragraph value (an integer between 0 to 255), and if the method reaches the end of the input stream, Returns -1. There are other forms of the Read method. These forms enable the program to read multiple bytes in one byte array: int in (byte b []); // Returns the number of bytes read, returns -1 if the end of the input stream is returned . INT read (Byte B [], int off, int LEN; // Returns -1 if the end of the read stream is returned. Where the OFF parameter specifies where the READ method stores the data in byte array B; the LEN parameter specifies the maximum number of bytes read by this method. 4. Close the stream Although Java automatically closes all open streams at the end of the program, it is a good habit when it is displayed when the end is used. An open stream may exhaust system resources. If you do not close the open streams, you may not get resources when this or another program is trying to open a new stream. Another reason for closing the output flow is to wash the content of the stream buffer (before the operating system is saved on the byte of the program to the input stream), the content is stored in the memory buffer). By calling a close () method, you can ensure that the operating system writes the contents of the stream buffer to its destination. Example: E35 (Example20_2) Second, the class corresponding to the FileoutPutStream class is the FileoutPutStream class. The FileOutputStream class provides basic file writing capabilities. In addition to the method of inheriting from the OutputStream class, the FileOutputStream class has 3 constructors: fileOutputStream (String name); // Create a FileOutputStream object fileOutputStream (file file) using a given filename Name; // creation with File object FileOutputStream Object FILEOUTPUTSTREAM (FileDescriptor fdobj); // Creating a FileOutPutStream object using the FileDescriptor object You can use the write () method to send bytes to the output stream: public void write (byte b []); // Write B.Length bytes to Output flow public void write (byte b [], int off, int LEN); // From the given byhenon array, write the LEN byte to the output stream, parameter b is data; OFF Is the start offset of the data; the LEN is the number of bytes to output. Example: E36 (Example20_3) Third, the FileReader class and the FileWriter class and the FileInputStream class and the FileOutStream class and the FileoutPutStream class are the FileReader class and the FileWr Iter class, which are subclasses of InputStream and OutputStream.

Its constructors are: FileReader (String filename); FileWriter (String filename); uses these two classes to handle FilenotFoundException exceptions. The following example is a code for creating a FileReader object, which can be read using this object to read the file named Student.txt. FileReader file = new fileReader ("student.txt"); Student.txt file stores a list of student, each name is occupied. If we want to read the name, you must read a line each time, but the FileRea DER class does not provide this method, so we must receive this stream (object) to another stream, read the list from the latter stream . Java provides classes called Buf FredReader, constructor is: bufferedReader (Reader IN); // can read text lines, method is readline (). Create a bufferedr EADER object by delivering a Reader object (such as the FileReader instance), the code is as follows: BufferedReader IN = BufferedReader ("student.txt"); then read the student list from the stream in in . Example: E37 (Example20_4) The following example is a code that creates a FileWriter object, which can use this object to write a file with Hello.txt. FileWriter Tofile = New FileWriter ("Hello.txt"); use Java's BufferedWriter class to receive a stream to Tofile, then use the BufferedWriter class: Write (string s, int off, int LEN); put characters String S is written in Hello.txt. BufferedWriter out = new bufferedwriter (New FileWriter ("Hello.txt")); Out.Write ("How are you", 0, s.length ()); but Out.write ("How are you", 0, s .length ()) just writes the string "how are you" into the buffer. If you want to write to the file, you must perform the statement: Out.flush (); write the buffer string to file hello.txtXT . Example: E38 (Example20_5) Fourth, use the file dialog to open and save files After learning the stream, we can use the File dialog box to open and save the file. In the following example, we display the contents of a file in a text area and save the content of the text area to a folder of the hard disk. Example: E39 (Example20_7) In the following example we use the File dialog to open a executable on the local machine.

When performing an executable on a local machine, you can use the Runtime class in the java.lang package. First use the Runtime class declare an object: Runtime EC; then use this class's static method getRuntime () Create this object: EC = runtime.getRuntime (); EC can call the exec (String Command) method Open the client's executable. Example: E40 (Example20_8) 5. The data created by the data stream DataInputStream class and the DataOutputStream class is called the data input stream and the data output stream. They allow the program to read Java raw data in style with the machine-independent style. That is, when we read a value, you don't have to care about how many bytes should be concerned about this value. DataInputStream (InputStream IN): Bringing the created data input stream into a stream specified by the parameter in to read data from the latter (read with the machine-independent style). DataOutputStream (OutputStream Out): Bringing the created data output stream to an output stream specified by the parameter OUT and then writing the data type of the Java data type by this data output stream to the output stream O UT.

Some methods of data stream: close (); Close flow readboolean (); read a Boolean readByte (); read a byte readchar (); read a character readDouble (); read a double precision floating point value Readfloat (); Read a single precision floating point value readint (); read an int value readlong () from the file; read a long value readshort (); read a short value readunSignedByte (); read An unsigned byte readunSignedShort (); reads an unsigned short value readutf (); reads a UTF string Skipbytes (int N); skip a given number of bytes WriteBoolean (Boolean V); put a Boolean Value is written as a single-byte value to write Writebytes (String S); writes a string Writechars (String S); writing a string WriteDouble (double V); writing a double precision floating point Writefloat (Float V); write Enter a single precision floating point value WriteInt (int V); an int value WRITELONG (Long V); a long value WRITESHORT (INT V); a short value WriteUTF (String S); writing a UTF string example: E41 (Example20_12) E42 (Example20_13) Use the StringTokenizer class analysis string Sometimes we need to analyze strings and break the string into a single word that can be used independently, these words are called language symbols. For example, for a string "WE Are Students", if we use spaces as separators of the string, then the string has 3 words (language symbol). For strings "we, are, student", if we use a Chinese comma as the separator of the string, then the string has 3 words (language symbol). When we analyze a string and break the string into a word that can be used independently, you can use the StringTokenizer class in the java.util package, which has two commonly used constructors: StringTokenizer (String s): is a string s Constructs a parser. Using the default separator collection, ie spacer (several spaces are seen to be a space), newline, carriage return, TAB, feeder. StringTokenizer (String S, String Delim): Constructs a parser for string s. The characters in the parameter DELIM are used as the separator.

For example: StringTokenizer Fenxi = New StringTokenizer ("We Are Student"); or StringTokenizer Fenxi = New StringTokenizer ("We, Are, Student", ",", we call a StringTokenizer object as a string analyzer. One analyzer can use the nexttoken () method to get the language symbol (word) by one by one, each time the next language symbol is obtained in the string whenever nametToken (). The language symbol is usually obtained by WHILE loop. In order to control the cycle, we can use the HasmoreToKens () method in the StringTokenizer class, as long as there is language symbol in the string, the method returns true, otherwise returns false. In addition, we can also call the countToKens () method to get a total of a total of language symbols. Example: E43 (Example5_7) E44 (Example8_6) E45 (Example20_6) E45 (Example20_6) Multi-thread mechanism for Java previously developed procedures are single-threaded, that is, one program has only one execution clue from the head. However, many processes in the real world are characteristics with multiple clues simultaneously. For example: We can watch TV while watching TV. Another network server may need to handle the request of multiple clients simultaneously. A large feature of the Java language is the built-in support for multi-threaded. First, threads in Java. Programs, process and thread programs are a static code that is Blueta executed by the application software. The process is a dynamic execution process of the program. It corresponds to a complete process that is loaded from the code, executes to the execution, which is also the process of the process itself from generation, developing to the demise. If the class is more than a process, then the bell is the beginning of the process, and the course bell is the end of the process. The thread is a smaller execution unit than the process. A process can generate multiple threads in its execution, forming a plurality of execution clues, each thread, that is, each thread also has its own generation, existence, and demise process, is also a dynamic concept. Just after the start of the class, there can be many different "threads", such as the teacher's explanation, the students' listening. Each process has a dedicated memory area, while the thread can share the same memory cells (including code and data), and utilize these shared units to implement data exchange, real-time communication and must-have synchronization operations. 2. Threaded status and lifecycle have a default primary thread each Java program. For applications, the main thread is the clue executing the main () method. For Applet, the main thread command browser loads and executes a Java applet. To achieve multi-thread, you must create a new thread object in the main thread. The Java language uses the Thread class and its subclass of objects to represent threads. New threads usually have to experience the following five states in its complete life cycle: (1) New: When a Thread class and its subclass are declared and created, the newborn thread object is in a new state. It has already had the corresponding memory space and other resources.

(2) Ready: After the new state thread is started, the thread queue is waiting for the CPU service. At this point it already has the runtime, once the turn can be used to enjoy C PU resources, you can get from the creation of it. The main thread starts its own life cycle independently. (3) Run: When the thread of the ready state is scheduled and obtained the processor resource, it will enter the operating state. Each THREAD class and its subclass have an important R UN () method. When the thread object is scheduled, it will automatically call the RUN () method of this object, and execute from the first sentence. The Run () method defines the operation and function of this thread. (4) Blocking: A thread that is executing If in some special cases, if the input output operation is required to be operated or required to perform, it will make the CPU and temporarily abort the self-employed execution and enter the blocking state. When it is blocked, it cannot enter the queue queue. Only when the cause is caused, the thread can be transferred to the ready state, re-enter the line queue to wait for the CPU resources to continue running from the original termination. (5) Death: Threads in the death state do not have the ability to continue to operate. Thread death has two, one is the normal running thread to complete its work, that is, the last statement of the run () method is executed and the other is the thread is mandatory in advance. 3. Thread scheduling and priority threads are in the ready state first enter the ready queue queue waiting processor resource, and there may be multiple threads in the ready queue. Multi-threading systems will automatically assign a thread priority to each thread, and the task is an urgent important thread, which is high; the opposite is low. When the thread is queued, the high priority thread can be ranked by the previous position, which can first enjoy the processor resources, and the higher priority thread can only wait until the high priority thread in front of it is completed. Get processor resources. For the same threads in the priority, follow the "advanced first out" principle of the queue, that is, the thread that first enters the ready state queue is prioritized to the processor resource, and then the thread service of the queue is then entered. When a thread queued in the ready queue is assigned to the processor resource, the thread is called "scheduling" or the thread scheduling manager is selected. The thread schedule manager is responsible for managing thread queuing and processor allocation between threads, generally equipped with a well-designed thread scheduling algorithm. In the Java system, thread scheduling is based on the "first-serving" principle based on the priority. Second, Java's thread class and Runnable interface 1. The Thread class Thread class combines a thread in the Java program that needs to have the properties and methods, mainly: (1) The constructor of the constructor Thread class has multiple, and the corresponding operations are as follows. Public thread (): Create a thread object. Public Thread (Runnable Target): Create a thread object, the parameter Target is called a target object that is created. Creating a target object Target is responsible for implementing the Runnab LE interface, giving the method body of the Run () method in the interface, and gives the operation and function of the thread in the method body. After creating a new thread object with a constructor, the relevant data in this object is initialized, so that the first state of the life cycle of the thread is entered (new).

(2) Thread priority Thread class has 3 static constants for thread priority: min_priority, max_priority, norm_priori type. Where min_priority represents the minimum priority, usually 1. Max_Priority represents the highest priority, usually 10. Norm _Priority represents normal priority, the default value is 5. Corresponding to a new thread, the system will follow the following principles to specify priority: New thread will inherit the priority of the creation of its parent thread. The parent thread refers to the thread that creates a new thread object statement, which may be the main thread of the program, or a user-defined thread. In general, the main thread has a normal priority. In addition, the user can modify the system automatically set thread priority by calling the SETPRIORITY (INT A) method of the Thread class, making it in line with the specific needs of the program. A value is: thread. min_priority, thread. Max _priority, thread. Norm_Priority. (3) Other main methods start the string START () method. The start () method will start the thread object so that it is transferred from the new state into ready state and enters the ready queue queue. Define the RUN () method of the thread operation. The RUN () method of the Thread class is the same as the function and effect of the Run () method in the runnable interface. It is used to define the operations performed after the thread object is scheduled, which is the system automatically call and the user program is not reference. In the thread class of the system, the run () method does not have specific content, so the user program needs to create a subclass of its own Thread class, and rewrite the RUN () method to overwrite the original Run () method. The SLEEP () method for temporarily sleeping threads. The scheduling execution of the thread is performed in accordance with its priority, and when the advanced thread is not completed, the lower thread does not have a chance to obtain the processor. Sometimes, the priority thread requires a prioritized thread to do some work to cooperate, or the priority high thread needs to complete some time-consuming operations. At this time, the priority high thread should make the processor, low priority Threads have the opportunity to perform. To achieve this, the priority thread can call the Sleep () method in its Run () method to give yourself to abandon the processor resource, sleep for a while. The length of the sleep time is determined by the parameters of the SLEEP () method. Sleep (int MillSecond): MillSecond is a sleep time in milliseconds. Sleep (int Millsecond, int nanosecond): nanosecond is a sleep time in nanosecond. The Yield () method of the aborting thread. You can use the Yield () method when you need to force the life cycle of a thread to terminate. The isalive () method that determines if the thread is unsatisfied. Before calling the yield () method, it is best to check if the thread is still survive, and the thread that does not exist may cause system errors.

The Thread class has a static method: currentthead (), judge the thread that is currently occupying the CPU. 2. Runnable Interface Runnable interface has only one method run (), all user classes that implement the runnable interface must implement this Run () method, which provides the method body and defines the specific operation. The Run () method in the runnable interface is a more special method that can be automatically identified and executed by the running system. Specifically, when the thread is scheduled and transferred to the operating state, it is performed by the operation specified in the RUN () method. So, a class that implements the runnable interface actually defines the operation of a new thread other than the main thread, and defines the operation and execution process of the new thread, which is one of the most important and most basic work that implements multi-threaded applications. Third, how to implement multithreading in the program to implement multi-thread in the program: Create a subclass of the Thread class or implement the runnable interface. Regardless of which means, programmers can control the key operations: (1) Defining the operation of the user thread, that is, defining the RUN () method of the user thread. (2) Establish a user thread example at the appropriate time. 1. Creating a thread with a Thread class In this way, the user program needs to create a subclass of its own Thread class (Thread in the java.lang package) and redefine its own Run () method in the subclass, this run () The method includes the operation of the thread. This program needs to be created with your own thread, just create an instance of a defined Thread subclass. When you create the thread calling the start () method starts running, the run () method is executed automatically. Example: E46 (EXAMPLE19_1) 2. Implementing the Runnable interface Example: E47 (Example19_2) In a specific application, which method is used to construct a thread body to depend on the specific situation. Typically, when a thread has inherited another class, when you want to create a new thread in this thread, you should construct a second method, that is, the Runnable interface is implemented. The applet is actually a thread of the browser. This thread is executed by the browser, and the browser automatically calls the init (), start () method in the small application. Therefore, you have to create a new thread in a small application, it is best to place the startup of the new thread in the start () method of the applet. Example: E48 (Example19_4) four, the static method of the Thread class SLEEP () Since the SLEEP () method can be called directly by the class name, the following statement can be used when the execution of the program is required: Thread. Sleep (Int Time); : E49 (EXAMPLE19_8) V. Thread Synchronization Java allows us to create multiple threads, when handling multithreaded problems, we must pay attention to this question: When two or more threads accesses the same variable, and a thread needs to modify This variable.

We deal with such problems, otherwise it may have a chaotic, such as a wage management person in charge being a wage list, and some employees are collecting salary. If this is allowed to make a chaotic. When processing threads, the first thing to do is to modify the method of modifying data with keyword synchronized. When a method uses the keyword sync hronized to modify, when a thread A uses this method, other threads must wait until the thread A is used. Example: E50 (eXample19_9) 6. Use Wait (), Notify () and NotifyAll () methods in a synchronization method When a thread is using a synchronous method (using synchronized modified method), other threads cannot use this synchronization method. . For synchronous methods, sometimes some special circumstances, such as when you queuing a movie ticket in a ticket window, if you give money to the ticket, the ticket seller has no change to find it, then you must wait, and Allows you to buy tickets behind, so that the ticket seller gets a change to you. When a variable is used in a synchronization method used, this variable needs to be in line with the needs of this thread after modification, then the WAI T () method can be used in the synchronization method, and the thread is waiting, and allowed Other threads use this synchronization method. Other threads If you don't need to wait when using this synchronization method, it uses the NOTIFYALL () method to end the end wait for the use of this synchronization method while using this synchronization method, and use this synchronization method again. If you use notify (), just notify the first thread end waiting. Example: E51 (Example19_10) Java Network Programming First, use URL1. Internet address "IP" represents Internet Protocol (Internet Protocol). A IP address uniquely identifies a computer on the Internet. There is no IP (IP (IP Protocol) address that you cannot distinguish between different computers on the Internet. 2. Using the URL positioning resource IP address uniquely identifies the computer on the Internet, and the URL identifies the resources of these computers. URL (Uniform Resource Locators: Uniform Resource Locator) acts as a pointer, pointing to web page, binary files, and other information objects on the web. When we enter, for example, http://www.dlrin.edu.cn/HOTLINK.HTML

When the URL is actually provided, the URL of the home page is provided. Because the web page resides on a computer connected to the Internet, you need to determine your computer when you reference the page, so the IP address plays an important role in the URL. Therefore, the URL naturally contains the IP address of the computer of a given resource, and the computer containing the resource is the host of the resource. We analyze the URL

http://www.dlrin.edu.cn/HOTLINK.HTML

The information contained: HTTP: A Protocol (HTTP) used. DLRIN.EDU.CN: The domain name address of the computer stored. HotLink.html: Resources. 3. The customer / server architecture of the client and server web is that the customer needs some type of information, and the server provides the information required by the client. Customers need to connect to the server and request information to the server; and the server sends information to the customer. The two work together, and they have their own. 4. Some basic network classes are some basic network classes provided by Java's network API (application interface), which are included in the Java.net package. The URL class provides many construction methods that can be used to create a URL. The simplest constructor only requires a string representing the URL resource: public url (string s); the following example uses this constructor to create a URL object URL: try {url = new url ("http: // www .dlrin.edu.cn ");} catch (malformedurlexception e) {system.out.println (" BAD URL: " URL); Creating a URL object in the Catch structure. But as shown above, don't bother. Once you have successfully created a URL object, you can practice other Java network features. For example, you can link in an additional web page in the applet. The following code implements this feature: getAppletContext (). ShowDocument (URL); you can use this method in your applet, because the getAppletContext () method is in the Applet class Defined, showdocu work () actually completes the job positioning to another web page, and only the URL is required in the program, and other work will be automatically completed by Java. Example: E52 (Example21_1) E53 (Example 21_3) Second, socket 1. Socket (Socket and Serversocket) IP Address Identifies a computer on the Internet, the port number identifies the process (program) that is running on your computer. A combination of port numbers and IP addresses derived a network socket. The port number is specified as a 16-bit integer (0 ~ 65535). Where 0 to 1023 is pre-defined service communication (such as HTTP occupation port 80, FTP occupation port 21, etc.). Unless we need to access these specific services, you should communicate with one of these ports in 1024 ~ 65535 to avoid port conflicts. When two programs need to be in communication, they can connect to the socket connection using the Socket class. We can connect the socket connection to a phone call. When the call is complete, any party of the talk can be speech at any time. But when you initially establish a call, you must have a call, and the other is listening to the ringtone. In this way, one of the calls is "customer", responsible for the listening party is "server".

2. Customer Corpled Socket Object (Socket) Client program uses the Socket class to establish a socket connection with the server. Its construction method is: socket (String host, int port); // Parameter Host is the server's IP address, Port is a port number. IOEXCEPTION exception occurs when it is created, so establishing the socket connection with the server is as follows: try {socket mysocket = new socket ("http://dlrin.edu.cn", 1880);} catch (ooException E ) {} After the socket is connected to MySocket, you can imagine a communication "line" has been established. MySocket You can get a input stream using the GetInputst Ream () method, then this input stream read the information of "Line" (but you can't read yourself into the "line", just as you can call. The other party's voice is the same). MySocket also uses the getOutputStream () method to get an output stream, and then write information to "Line" with this output. When writing a program, the input obtained by MySocket uses the GetInputStream () method to flow over to another data stream (and the connection in the file input and output flow), then read from this data stream Information from the server, this is done because the DataInputStre AM has a better way to read information from the stream. The same truth, the output stream obtained by MySocket using the GetOutputStream () method is connected to another DataOutputStream data stream, and then writes the information to this data stream to send it to the server. 3. Establishing a server socket (ServerSocket) that accepts customer sockets is responsible for establishing a customer's socket connection, that is, the customer is responsible for call. Therefore, the server must establish a server socket waiting for the receiving customer socket. The server-side program uses the ServerSocket class to establish a server socket that receives the customer's socket. Its constructing method is: Serversocket (INT port); // Port is a port number. Port must be the same as the port number of the customer call. IoException exception occurs when establishing server sockets, so it should be established as described below: try {serversocket server_socket = new serversocket (1880);} catch (ooException e) {} When the server's socket connection server_socket is established Once, you can use the accept () method to receive the customer's socket MySocket.

Server_socket.accept (); Receiving the process of receiving customer sockets may also happen to establish a customer's socket: try {socket sc = server_socket.accept ();} catch (ioException e) { After receiving this customer's MySocket, put it in a declarative socket object SC, then the SC is MySocket (when Serve R_Socket receives another customer socket, such as herSocket, you can put it again Another Socket object). Such a server-side SC can use the method getOutputStream () to get an output stream, and then use this output to "line" write information, sent to the client. You can use the GetInputStream () method to get an input stream, and then read the information in "Line" with this input stream. After the communication is completed, the socket connection is closely closed: sc.close (); Example: E54 (Example21_4) 4. Put the socket connection in a thread to the socket connection involved in the input stream and output flow operations. In order not to affect our other things, we should put the socket connection in a separate thread. In addition, after the server receives a customer's socket, it should start a thread specially serving the customer service. Example: E55 (Example21_5) Java and Database Connection (JDBC Technology) JDBC (Java Database Connectivity) is a Java database connection API. Simply put, JDBC can complete 3 things: (1) establish a connection with a database; (2) Send a SQL statement to the database; (3) Process the result of the database returned. JDBC is very similar to ODBC design. One way of establishing a connection in JDBC and database is to build a JDBC-ODBC bridge. Because the ODB C driver is widely used, after building such bridge, the JDBC has the ability to access almost all types of databases. First, set the data source to have a database designed with Access: Student.mdb, there is a table in this library, the name of the table is chengjibiao. In order to establish a connection with this database, first configure an ODBC data source. Suppose the operating system is WindowsXP, open the control panel in WindowsXP, select "Performance and Maintenance" - "Management Tool", Double-click "Data Source (O DBC)", select "System DSN" - Add "-" Microsoft Access Driver * .mdb ", click the" Finish "button to enter the" ODBC Microsoft Access "window, enter the data source" Redsun ", click the" Select "to enter the" Select Database "path window, select the database directory and database name Student. After MDB, confirm and leave step by step. (P285) Click the "Advanced" button to set "Login Name" and "Password".

Second, JDBC-ODBC Bridge 1. Building a JDBC-ODBC Bridge Now We have a data source, which is a database. In order to connect to this database, first load the JDBC-ODBC Bridge driver, establish a JDBC-ODBC bridge: Class.Forname ("Sun. Jdbc. ODBC. JDBSODBCDRIVER"); Class is a class in java.sql This class can establish a JDBC-ODBC bridge by calling its static method forName (). An exception may occur when establishing a bridge, so this exception must be captured. So the standard method for establishing a bridge is: try {class.forname ("Sun. JDBC. ODBC. JDBSODBCDRIVER");} catch (classnotfoundexception e) {} 2. Connecting to the database first using the Connection class in the package java.sql declares an object, then use the class DRIVERMANAGER to call its static method GE tConnection () Create this connection object: Connection Con = DriverManager.getConnection ("JDBC: ODBC: Data Source Name "," Login Name "," Data Source "); If there is no login name and password for the data source, then the connection form is: Connection Con = DriverManager.getConnection (" JDBC: ODBC: Data Source Name " , "", ""); So in order to exchange data with data source REDSUN, create the connection object as follows: Connection Con = DriverManager.getConnection ("JDBC: ODBC: Redsun", "Snow", "OK"); establish a connection It should be captured to capture the SQLEXCEPTION exception. Try {Connection Con = DriverManager.getConnection ("JDBC: ODBC: Redsun", "Snow", "OK");} Catch (SQLEXCEPTION E) {} This is established to the database Student.mdb connection. 3. Send a SQL statement to the database First, use Statement to declare an SQL statement object, and then create this SQL statement object by the object CON call CREATEME NT () method created by the connection database you just created. Try {statement SQL = con.createstatement ();} catch (sqlexception e) {} 4. After processing the query results After the SQL object, you can invoke the corresponding method to implement queries and modifications to the database.

And store the query results in an object of a RESULTSET class declaration, that is, the SQL statement will return a ResultSet object on the query operation of the database: ResultSet RS = SQL.ExecuteQuery ("SELECT * FROM transcript"); ResultSet object is actually It is a tubular data set, that is, it consists of a data line of a column organization in a unified form. The ResultSet object can only see a data line at a time, and use the next () method to go to the next data line. After getting a line of data, the ResultSet object can use the location index (first column using 1, second column using 2, etc.) or use the column name to use the getxxxx () method to obtain a field value. Several methods ResultSet object: boolean next (); byte getByte (int columnIndex); Date getDate (int columnIndex); double getDouble (int columnIndex); float getFloat (int columnIndex); int getInt (int columnIndex); long getLong (int columnIndex); String getString (int columnIndex); byte getByte (String columnName); Date getDate (String columnName); double getDouble (String columnName); float getFloat (String columnName); int getInt (String columnName); long getLong (String columnName String getString (String ColumnName); Example: E56 (Example23_2) The event source of the mouse event and the keyboard event in Java is often a container, when the mouse enters the container, leaves the container, or click the mouse in the container. A mouse event occurs when dragging the mouse. First, use the mouselistener interface to handle the mouse event 1. There are five mouse events that occur in the event source: Press the mouse button, release the mouse button, mouse button, mouse to enter and exit. The type of mouse event is MouseEvent, that is, when a mouse event occurs, the MouseEvent class automatically creates an event object. There are several important methods in the MouseEvent class: getX (), get (): Get the coordinate position of the mouse. getModifiers (): Get the left or right key of the mouse. GetClickCount (): Get the number of times the mouse is clicked. 2. The event source obtains the monitor's method is AddMouseristener.

3. The interface that handles the event source occurs is Mouselistener. There is a method in the interface: MousePressed (MouseEvent): Responsible for handling the mouse to press the event. That is, when the event source presses the mouse, the monitor discovers this event to process the method in the automatic call interface. MouseeleleaseD (MouseEvent): Responsible for handling mouse release events. That is, when the mouse is released in the event source, the monitor discovers this event to process the method in the automatic call interface. MOUSEENTERED: Responsible for handling the mouse to enter the container event. That is, when the mouse enters the container, the monitor discovers this event to process the method in the automatic call interface. MouseExited (MouseEvent): Responsible for handling the mouse to leave the container event. That is, when the mouse leaves the container, the monitor discovers this event to process the method in the interface. MouseClicked (MouseEvent): Responsible for handling Click on the mouse event. That is, when the mouse is hit, the monitor discovers this event to process the events in the event. Example: E57 (EXAMPLE18_1) Second, using the MouseMotionListener interface to handle the mouse event 1. There are two mouse events that occur in the event source: drag the mouse and move the mouse (the mouse button is not pressed). The type of mouse event is MouseEvent, that is, the MouseEvent class automatically creates an event object when such an event occurs. 2. The event source obtains the monitor's method is AddMouseMotionListener (monitor). 3. The interface that handles the event source occurs is MouseMotionListener. There is a method in the interface: mouseDragged (MouseEvent): Responsible for handling the mouse drag event. MouseMoved: Responsible for handling mouse movements. Example: E58 (EXAMPLE18_6) Third, control the mouse pointer shape When a mouse event occurs, you can use the setCursor () method to set the mouse pointer shape, all components inherit this method from their parent class. Listed below are definitions of common shape of the mouse pointer on the Windows platform: HAND_CURSOR MOVE_CURSOR WAIT_CURSOR CROSSHAIR_CURSORNE_RESIZE_CURSOR SE_RESIZE_CURSOR N_RESIZE_CURSOR E_RESIZE_CURSOR example: E59 (Example18_8) Fourth, the keyboard event when pressed, released, or tap on the keyboard keyboard event occurs when a key . When a component is active, it can be an event source that occurs a keyboard event. The event source uses the AddKeylistener method to get a monitor. The monitor is an object that created the class of the object to implement the interface Keylistener.

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

New Post(0)