Introduction to GUI Programming
Event-driven Programming: program responds to these events. The order of the events is determined by the user, not the program. This is similar to going to a hardware store to get components for your home improvement project. Most of the components you need already exist. All you need to do is to install them.
Java GUI Programming:A user interacts with a GUI application by causing events. The application must respond to events in the order they arrive.
Three Parts of a GUI Program:
- Graphical Components make up the Graphical User Interface.
- Listener methods receive the events and respond to them.
- Application methods do useful work for the user.
The graphical components are Swing objects. You may use them without change or may extend them to make your own classes. Listener methods and application methods are Java methods that you write. Listener methods respond to events by calling application methods. Application methods are ordinary Java methods that perform useful computations. They receive data from the GUI and send data to the GUI to be displayed, but are not usually themselves concerned with the user interface.
To write a GUI application, keep these three types of software separated (while keeping the big picture in mind). In a big software project an entire team of programmers is assigned to each of the tasks.
Container Classes: A GUI program consists of a collection of graphical components that are all placed inside one or more windows. A container is an object that can hold other GUI components. In Java terminology, a window (such as the browser window you are looking at) is a container. The buttons, sliders, icons and other GUI components are contained (by the container).
AWT Hierarchy: Some of the AWT classes derived from Component are Button, Canvas, and Container. The JComponent class is derived from Container and is one of the base classes of Swing. The JFrame class is derived from the AWT Frame class. It is usually the main container for a GUI application.
JComponent class: Objects of classes based on Container have common characteristics. They can contain components, they themselves can be placed inside containers, they can be displayed on the monitor, they generate events, they register event listeners, and so on. Since all Swing classes have Container as an ancestor, all Swing objects have these characteristics.
Swing JFrames:
Frames: In Java, a frame is a window that has nice borders, various buttons along the top border, and other features. What you usually call a "window" Java calls a "frame". A frame is a container object, so GUI components can be placed in it. a frame object is actually a section of main memory that holds information and methods. With the help of the operating system and the graphics board.
Small GUI Program
First a JFrame is created by invoking its constuctor. The argument to the constructor sets the title of the frame. The setSize(200,100) method call makes the rectangular area 200 pixels wide by 100 pixels high.
The setVisible(true) method call makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen. A call to setVisible(false) makes the frame invisible, but does not destroy the software object.
It is easy to forget to include setVisible(true). If you run your GUI program, and nothing happens, check that you have called this method.
The setDefaultCloseOperation() method picks the action to perform when the "close" button of the frame is clicked. This is the little button usually at the top right of the frame. If you forget to call this method with the appropriate constant, clicks on the close button will be ignored.
Running the GUI Program:
The usual way of writing a GUI is to define your own class by extending the JFrame class.
The drawString() method: When the Java system needs to paint a MyFrame object it first draws most of the picture and then calls paint() in the MyFrame object to do whatever extra the programmer wants. The first part of the work is vital. It involves interacting with the graphics of the computer system and controling the graphics board. The parameter g is a reference to a Graphics object. The Graphics object represents the part of the frame that you can draw on. When the system calls paint(), the system provides a value for this parameter. One of the methods of Graphics is drawString(String st, int X, int Y) which draws a string on the graphics area at location starting X pixels from the left and Y pixels from the top.
Buttons and Actions
JButton->AbstractButton->JComponent->Container->Component->Onject
To construct a JButton object, use new. Then add the button to the frame's content pane. The content pane is a container that represents the main rectangle of the frame. To get a reference to the content pane, use the getContentPane() method of the frame. The add method of a content pane puts a JButton (or other component) into the frame.
The ButtonFrame class does not to define a paint() method because everything in the frame is a Swing component. The system will automatically paint all components in a container when it needs to. If special processing is needed, (as with drawString() in the previous chapter), then you need to override paint().
The program in the previous chapter did not define a constructor because the constructor it inherited from its parent class JFrame was enough to do the job. ButtonFrame adds a components, and this should be done in a constructor.
Layout Manager:
When you add() buttons (and other components) to a content pane, a layout manager automatically decides what size they will be and where they will go. This is convenient, because you can add components without worrying about the details. The layout manager is like a little artist inside the computer. You say what components you want and the layout manager lays them out in the picture.
The layout manager sometimes makes odd choices. However, there are several kinds of layout managers. Each layout manager has a different style of positioning components. Usually there is a layout manager that will do the job you want. If you don't specify otherwise, a default layout manager is used.
Our program will look better if it uses the FlowLayout manager. The FlowLayout manager puts components into the frame row by row in the order they are added.
Event Listener Object
For a program to respond to an event there must be an event listener object for it. The event listener object contains listener methods for various types of events
Event Object
An event listener is an object that "listens" for events from a GUI component, like a button. An event is represented as an object. When the user generates an event, the system creates an event object, which is then sent to the listener that has been registered for the GUI component.
To be able to respond to events, a program must first:
Create an event listener object for the type of event.
Register the listener object with the GUI component that generates the event (or with a component that contains it).
ActionListener
A button listener class must implement the ActionListener interface. ActionListener is an interface (not a class) that contains the single method: public void actionPerformed( ActionEvent evt) ;
The ActionEvent parameter is an Event object that represents an event (a button click). It contains information that can be used in responding to the event. Since ActionListener is an interface, you use it with a class that will implement the actionPerformed() method. It is common to implement the interface in the same class that contains the button(s):
For the ActionListener interface, there is only one method: actionPerformed().
The repaint() method called in actionPerformed()tells the system to repaint the screen sometime soon because we have changed something. The system will do this when it is ready. Don't call paint().
The frame will be the listener for the button.
button's life in a frame:
- JButton newButton=new JButton(***) ; //create a new JButton object and assign to newButton
- newButton.addActionListener(this);//addactionlistener
- getContentPane().add(newButton);//add into JRame
- public void actionPerformed(ActionEven e){***}//action performeed. everytime, when a even happened, such as mouce moved, if such kind of event has been registed, than a even object is created and have certain action performeed, after performed, then program executes next statement or event, or this performemt will not stop. so we can see is a button is released on show which means relevant actionPerformed has been successed done. if this even is not registed, system just ingnore them.
Buttons and Action Events
setActionCommand() and getActionCommand() method refer to different action, it will pass or return String to distingish different button event. which can help us to deal with different event in actionPerformed() method.
Swing Text Fields and Labels:
A Swing Component: JTextField
A JTextField is a box that contains text. The user can type text into the box and the program can get it and then use it as data. The program can write the results of a calculation to a JTextField.
To enter text into the field you must first click the mouse pointer inside of it. This gives the field the keyboard focus (usually just called focus). When a component has focus, characters from the keyboard are directed to that component. A component gets focus by various means. The user might click it, or the program might give it focus.
JTextArea+JTextField+JEditorPane -> JTextComponent->JComponent->Container->Component->Object
The JLabel Class
In a typical application with a graphical interface, about 40% of the code manages the user interface. The rest of the code is for the application--the reason the program was written. Usually the application code is kept separate from the code that manages the interface. In a big application it would be confusing to mix the two together.
The GUI components from Swing can be used by applets.
It is a good idea to keep the GUI code and the application code in separate modules to help in debugging and understanding the program. This is also helpful if you later need to make changes to the program, say changing it from an application to an applet. The application code can be carried over without change.
The user can type into a JTextField even if it does not have a listener. getText() will still work
JPanel and BoxLayout
Each panel uses its own layout manager for the components it contains. The default layout manager of JPanel is flow layout, which is often ideal. But you may use another layout manager if appropriate.
BoxLayout Layout Manager
BoxLayout. This layout manager aligns components either horizontally or vertically within a pane. BoxLayout(Container box, int axis)
box: the container this layout manager is for axis: BoxLayout.X_AXIS -- for left to right alignment BoxLayout.Y_AXIS -- for top to bottom alignment . box is a reference to the container which will be managed by this layout manager. Often the container is a content pane.
This idea of nesting panels is a powerful one. It may look complicated and tedious, but it is much less so than laying out a design on graph paper and specifying the exact size and location of all the components. Such a design has no flexibility. What happens if you want to add or delete a component? Everything must change. With Java's layout managers everything is dynamically adjusted.
Radio Buttons, BorderLayout, and Glue
Radio Buttons
Usually radio buttons are placed in (1) a panel, to control how they are displayed, and (2) a button group, to control which buttons may be active simultaneously. A button group is an object which must be constructed. Radio buttons are then added to it.
Radio buttons generate action events which require a registered action listener. Do this as with JButtons. Use setActionCommand() to assign a command string to each button. Use addActionListener() to register a listener for each button, usually the same listener for all the buttons in a group. Use getActionCommand() in the action listener to determine which button was pushed.
BorderLayout
BorderLayout.is a frequently used layout manager. The container it manages corresponds to a rectangle on the screen. That rectangle is divided up into five regions:
- BorderLayout.NORTH,
- BorderLayout.SOUTH,
- BorderLayout.EAST,
- BorderLayout.WEST,
- BorderLayout.CENTER.
Each region may hold only one component, although that component may be a panel (and usually is). The panel may contain several components. The layout manager adjusts the size of the regions depending on what is in them. You don't have to put a component in each region. If a region has no component in it, it shrinks to a small area.
Class Box
Layout managers sometimes jam components together in a way that makes the layout look cramped. The class Box can help in this situation. A Box object is a container similar to a panel, but lacking some features. The default layout manager of Box is BoxLayout. However, the most useful features of class Box are its methods that create invisible components. These components correspond to rectangular areas of the screen. They are used as spacers to separate the visible components. If you have ever set type you know how useful spacers are in creating an attractive page. To create a fixed-sized invisible component use the method: Box.createRigidArea( new Dimension( int width, int height ) )
The parameter to createRigidArea()is a Dimension object, which does little more than hold a width and a height.
All GUI components have a getSize() method that is used to determine the dimensions of the component. The dimensions may change as a program executes, so this is a useful method. To determine the current size of a frame, use: Dimension JFrame.getSize()
Then it can look at the height and width fields of the Dimension object. Using this data it can create a rigid area of appropriate size. If this is too complicated, then use glue.
The glue component is another invisible component that class Box creates. Think of glue as stretchy caulking between components. It keeps them separated, but expands or shrinks as needed.
To create glue use one of the following:
- Box.createHorizontalGlue()
- Box.createVerticalGlue()
Class JSlider
JSlider( int orientation, int min, int max, int init )
orientation: SwingConstants.HORIZONTAL or SwingConstants.VERTICAL
min: the minimum value. The value when the slider is at the extreme left (or very bottom) of its range.
max: the maximum value. The value when the slider is at the extreme right (or very top) of its range.
init: the initial value of the slider
- JSlide silderV=new JSlide(SwingConstants.HORIZONTAL, 0, 100, 79)
- slideV.setMajorTickSpacing(10);
- slideV.setMinorTickSpacing(10);
- sliderV.setPaintTicks(true);
- sliderV.setPaintLabels(true);
- sliderV.setSnapToTicks(true);
setPreferredSize()
The layout managers have control over the size of components, but often do their job better if you indicate a preferred size. This is done with setPreferredSize( new Dimension( int width, int height )
If this is not used, the graphical representation of a slider often has its labels and tick marks crowded together
A listener for a slider implements the ChangeListener interface. This interfaces has a single method: public void stateChanged(ChangeEvent evt)
An object that implements the interface must be registered with the slider in order to receive events: slider.addChangeListener( ChangeListener lstn )
There may be several sliders in your user interface. They all generate change events. If one change listener listens to all these events it is convenient to give the sliders names so that the events can be sorted out correctly. (Another way is to register its own listener with each slider). A name is a string that can be assigned to any object that inherits from class Component. Assign it using: component.setName( String name )
Of course you must make sure that components that share the same listener have unique names.
The Object getSource() Method
An event object contains a reference to the component that generated the event. To extract that reference from the event object use: Object getSource()
Since the return type of getSource() is Object you typically use a type cast with it: // listener method
public void stateChanged( ChangeEvent evt )
{
JSlider source;
source = (JSlider)evt.getSource();
. . . .
}
Now that you have a reference to whichever slider caused the event you can use any of the slider's methods.
Assume that the slider has a name you have set using setName(). The name of the slider is a string that is stored as part of its data. To ask the slider for its name use: String getName()
Then, to get the value of the slider use int getValue()
The value is an int between the minimum and maximum value of the slider.
In the previous application the number in the text box changes continuously as the knob is moved. Usually this is desirable. But sometimes the application calls for a great deal of work and you don't want to do it for each change event. There are (potentially) hundreds of change events generated in moving the knob from one value to the next. While the value is still changing the listener should discard the event. boolean getValueIsAdjusting()
This method returns true while the knob is still moving.
No comments:
Post a Comment