Java basic knowledge of graphics programming notes -11_1-

Java basic knowledge of graphics programming notes -11_1-

11_1 Graphics Programming

1 Swing Overview

Now, Swing is not based on formal names such as GUI toolkit. It has been part of the Java Foundation Classes (Java Foundation Class, JFC) is. Full JFC is very large, much larger than the content contained therein Swing GUI toolkit.

Swing JFC contains not only characteristic components, but also contains a accessibility the API, a 2D API and a drag API.

Notes: Swing does not completely replace the AWT, but based on the AWT architecture. Swing only provides the ability to more powerful user interface components. Especially in the procedures used in the preparation of Swing, AWT also need to use basic office
management events. From now on, Swing is a user interface class "be drawn"; AWT refers to as event handling mechanism underlying this window toolbox.

Of course, the display element Swing based user interface based on other than the display assembly of AWT slower speed on the user's screen. Given past experience, any of a modern computer, the slight difference in speed anyway cause illness. In addition, due to the following points irresistible, people choose Swing:

  • Swing has a rich, convenient user interface elements of the collection.
  • Swing little about the underlying platform dependent, so few platform-specific bug.
  • Swing to give users the feeling of different platforms consistent.

However, the third point above, there is a potential problem: If the user interface elements look the same on all platforms, so they are likely to be different and local control, and users of these platforms may not be familiar with this.

Swing uses a very clever way to solve this problem. When writing Swing programmer, you can specify a special "look and feel" for the program.

In addition, Sun has developed a platform-independent of perception called Metal. Now, the market people it called "Java look and feel." However, the vast majority of programmers also continue with Metal term, this book will also be so called.

Some critics Metal a bit clunky, but in Java SE 5.0, but looks brand new (see Figure 10-3). Now, Metal exterior supports a variety of topics, there are small changes each theme colors and fonts. The default theme is called Oceano in Java SE 6, Sun improved support for Windows and GTK native look and feel. Swing applications will support color theme of personalization, realistic performance with dynamic buttons and scroll bars become very fashionable.

2 Create a frame

In Java, the top-level window (the window is not included in the other window) is called a frame (frame). There is a class called Frame in AWT library is used to describe the top-level window. Swing version of this class is called JFrame, it extends to Frame class. JFrame is one of the very few not drawn on the canvas Swing components. Therefore, it is modified components (buttons, title bars, icons, etc.) drawn by the user's windowing system, rather than drawn by Swing.

Warning: Most Swing component classes all begin with "J", for example, JButton, JFrame and so on. Such classes have Button and Frame in Java, but they belong to AWT components. If you accidentally forget to write "J", the program still can be compiled and run, but mixed together using Swing and AWT components will result in inconsistent visual and behavior.

In this section, related to the common methods described in the JFrame Swing. Listing 10-1 shows a simple program that displays an empty frame on the screen

//程序清单10-1 simpleframe/SimpleFrameTest.java
package simpleFrame;
import java.awt.*;
import javax.swing.*;
* ©version 1.33 2015-05-12
* author Cay Horstmann

public class SimpleFrameTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
                SimpleFrame frame = new SimpleFrame();
                frame.setDefault(CloseOperationJFrame.EXIT_0N_CL0SE);
                frame.setVisible(true);
            });
    }
}
class SimpleFrame extends JFrame {
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 200;
    public SimpleFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }
}

The following line by line to explain the program.

Swing class located in the javax.swing package. Javax package name indicates that this is a Java extension package, rather than the core package. For historical reasons Swing class is considered to be an extension. But from version 1.2, Java SE implementations on each contain it.

By default, the frame size is 0x0 pixels, this framework there is no practical significance. Here the definition of a subclass SimpleFmme, its constructor the frame size is set to 300 x 200 pixels. This is the only difference between SimpleFrame and JFrame.

In the main method SimpleFrameTest class, we construct a SimpleFrame object is to make it visible.

Swing in each program, there are two technical issues it needs to be emphasized.

First, all Swing components must dispatch thread (event dispatch thread) is configured by the event, mouse clicks and button thread will transfer control to the user interface components. The following snippet of code is executed in the event dispatch thread:

EventQueue.invokeLater(() -> {
    statements
});

The content will be discussed in detail in Chapter 14. Now, simply start it as a magical Swing program code.

Next, the definition of a response operation when the user closes the frame. For this program, only to let the program simply exits. Select this action in response to the statement frame.setDefaultCloseOperation(JFrame. EXIT_0N_CL0SE);

The program comprising a plurality of frames, can not let the program exits when the user closes a frame therein. By default, when the user closes the window frame will only hide, but the program is not terminated (after the final frame is not visible, then the program is terminated, this treatment is appropriate, while Swing is not the case work).

Simple framework construction is not automatically show up, the frame is not visible at first. This gives programmers an opportunity to go to the first show of the added components in the framework. In order to show the framework, main method needs to call setVisible method framework.

After the initialization statement, main method exits. It should be noted, main exit did not terminate the program, but the main thread terminated. Event dispatching thread remains active program until you close the frame or call System.exit method to terminate the program.

Shown in Figure 10-5 is the result of Listing 10-1 run, it's just a very boring top-level window. Seen in this figure, the title bar and frame decoration (for example, reset the window size of the corner) are drawn by the operating system, rather than the Swing library. The same program runs under Windows, GTK or Mac, get different decorative frame. Swing library is responsible for drawing everything within the framework. In this program, only the frame is filled with a default background color.

Note: You can call to frame.setUndecorated(true)turn off all decorative frame

3 frame positioning

Superclass inherit many methods used to process frame size and position of the most important are the following number:

  • setLocation setBounds and a method for setting the position of the frame.
  • setlconlmage used to tell the system which icon is displayed in the window title bar, task switching window and other locations.
  • setTitle used to change the title bar text.
  • setResizable using a boolean determining whether the size of the frame to allow the user to change.

Figure 10-6 shows the inheritance hierarchy JFrame class.

    Object
       |
       |
    Component
       |
       |
    Container
       |
       |
JComponent  Windows
    |          |
    |          |
JPanel      Frame
           |
           |
        JFrame

Of the Component class (it is the ancestor of all GUI objects) and the Window class (Frame is a superclass) need to study it carefully, and change the framework of the scaling method to find. For example, setLocation Component class method is a method of re-positioning assembly. If the call setLocation(x, y)is placed in the position of the upper left corner of the window horizontal pixels x vertical pixels y coordinates (0,0) in the upper left corner of the screen.

Likewise, the setBounds Component method may be implemented in a single step weight positioning assembly (particularly the JFrame) size and position, for example:

setBounds(x, y, width, height);

Window system allows the control window position, if called before the display window

setLocationByPlatform(true);

Window will be chosen position of the window (not size), typically last from a small window display location offset.

Note: For frame is, setLocation and coordinate setBounds thus relative to the entire screen. Shall see Chapter 12, referred to the coordinates of the components contained in the vessel are relative to the container.

3.1 Frame Properties

The method is based on many acquisition component class / method is provided for the form of, for example, the following method of the Frame class:

public String getTitle();
public void setTitle(String title);

Such a method of setting an attribute for acquiring is referred to. Property contains the attribute names and types. After the first letter lowercase to get or set can give the corresponding attribute name. For example, Frame String class has a property called type and title.

Conceptually, title is an attribute of the frame. When setting this property, I hope this title can change the display on the user's screen. When acquiring the property, hoping to return the property value has been set.

We do not know (or care) how the Frame class is an implementation of this property. Perhaps simply use peer storage frame title. Perhaps there is an instance domain:

private String title; // not required for property

If the class does not match the instance fields, we will not know (or care) how to get and set methods. Perhaps just reading, writing and instance fields, and perhaps also perform many other operations. For example, when the title changes, the system informs the window.

For get / set convention with one exception: For type boolean property, acquired by the beginning of the method is. For example, the following two methods define locationByPlatform properties:

public boolean islocationByPIatforn()
public void setLocationByPIatforra(boolean b)

4 shows the assembly information

The message string can be drawn directly in the frame, but this is not good programming practice. In Java, the frame is designed to hold the container assembly, may be a menu bar, and other user interface elements placed therein. Under normal circumstances, the information should be drawn on the other component, and this component is added to the framework.

JFrame quite a complicated structure. JFrame shows the structure in Figure 10-8. Can be seen, there are four panel JFrame. One of the root panel, the panel and glass panel level and people do not care; they are used to organize the menu bar and content pane and achieve the look and feel.

Swing programmers are most concerned about is the content pane (contentpane). In the design of the frame, when to use the following code to add all of the components to the content pane:

Container contentPane = frame.getContentPane() ;
Component c = ...;
contentPane.add(c) ;

In 1.4 and previous versions of Java SE, add JFrame class method throws an exception message “Do not use JFrame.add().Use JFrame.getContentPane().add instead”. Today, JFrame.add method is no longer displayed

The message, simply call add content pane, so you can directly call

frame.add(c) ;

Here, a drawing assembly intended to be added to the message frame. A drawing assembly, to define an extended JAComponent class, and a method wherein the cover paintComponent.

Graphics paintComponent method has a type parameter, which holds provided for drawing text and images, for example, set the current font or color. In Java, all drawing must Graphics object, wherein the method comprises a drawing pattern, images, and text.

Guess you like

Origin www.cnblogs.com/whatsabc/p/11520901.html