How to program a gui in java




















Contains the form's non-visual components. To select a component in the window click its icon. Without releasing the mouse button, drag the component to the desired location in the form. If you want to add the component to the Other Components node, drag the component to the white area outside the form in the GUI Editor's workspace. To add multiple components from the Palette:. If you want to add the component to the Other Components node, click in the white area outside the form in the GUI Editor's workspace.

To add a component using the Navigator window:. To add a bean from the Projects, Files, or Favorites windows:. In the Files window, locate the bean's class node. The class must be a bean and it must be compiled. For a class to be a bean, it must be possible to create an instance of the class using an empty public constructor. Right-click the class node and choose Copy from the contextual menu. The IDE adds the bean to the current form. When working with nested containers, it is sometimes difficult to select the container to which you want to add the component.

You must first select the desired container before selecting the component you want to add. You then select the component from the window, hold down the Alt key, and click the desired container again to add the component.

Selecting a component in one window automatically selects it in the other. To select multiple components, do one of the following:.

Hold down the Control key while clicking multiple components in the Form Editor or while clicking multiple nodes in the Navigator window. In the GUI Builder, hold down the Shift key while holding down the left mouse button and drag the mouse over each component in the group.

A rectangle is painted as the mouse is dragged over the group of components. When the mouse button is released, all the components included in the rectangle are selected. When working with nested components components within a container like a panel for example , clicking in the GUI Builder always selects the deepest component at the point of the click. You can, however, select nested components on different levels using modifier keys, as described below.

Right-click to display the contextual menu for the selected container or subcomponent. The right-click action does not change the selection depth. To select the parent container of a selected component:.

If the currently selected component does not have a parent container i. To select a subcomponent of a selected container:. If the currently selected component does not contain any subcomponents, the container component for the entire form is selected. Click the appropriate align button in the GUI Builder toolbar.

The IDE shifts the component positions such that the specified edges are aligned and the component anchoring relationships are updated. A horizontal guideline appears indicating that the selected component's baseline is aligned with the baseline of the second component and a vertical guideline suggest the spacing between the two components.

Click to position the component. The IDE snaps the second component into a position aligned with the baseline of the first and displays status lines indicating the component spacing and anchoring relationships. When guidelines appear indicating that the first component's left edge is aligned with that of the JLabel, move it further to the right until secondary indentation guidelines appear.

For more information of working with components see Section It is often beneficial to set several related components, such as buttons in modal dialogs, to be the same size so they can be easily recognized as offering similar functionality. You can also adjust the resizing behavior of components to ensure that component relationships are maintained at runtime.

The IDE sets the selected components to the same size and adds small graphic to indicate the component relationships. The IDE sets the components auto-resizing behavior to resize horizontally at runtime. The alignment guidelines and anchoring indicators are updated to indicate the new component relationships. Once you have added a component to a form, you can edit values in the Properties window to modify its behavior and appearance. If you select multiple components, their common properties are displayed and any modifications apply to all of the selected components.

Optional If the property you want to edit has an ellipsis Optional If you are using the property editor, use the Select Mode combo box to choose between available custom editors for the property, make the necessary changes, and click OK.

To return a property to its default value:. Right-click the property name and choose Restore Default Value from the contextual menu. The IDE returns the selected to its default value. Use the Connection wizard to set events between two components within a form without having to write code manually. To set an event using the Connection wizard:. Section On the Connection wizard's Select Source Event page, expand the event type directory node and select the event that the trigger component fires from the Events list.

Accept the default handler method name or type in a new name and click Next. On the Specify Target Operation page, specify the operation to be performed on the target component by selecting the appropriate radio button and choosing from the list of operations.

If you choose a method call with no parameters, the wizard's Finish button becomes available. Optional If you wish to enter event handler code directly, click the User Code radio button and click Finish.

The insertion point is placed in the new event handler in the Source Editor, where you can write the event handler code yourself. For more information see Section On the Enter Parameters page, specify the values for each tab's target property or method by selecting the source from which each parameter's value is acquired. The source code generated for each of the parameters is displayed in the Generated Parameters Preview field.

The Java programming language uses events to enable GUI form behavior. Source objects can trigger events which one or more objects with event listeners react to by means of event handlers. You can define event handlers using a component's property sheet or contextual menu. You can also define an event handler using the Connection wizard. To define an event handler using the property sheet:. Click the Events button at the top of the Properties window.

Click the value of the desired event in the list. Click the event's ellipsis Click the Add button to add a new name to the list of handlers. Click OK. To define an event handler using the contextual menu:. Choose Events from the contextual menu and its submenus. Bold menu items in the Events submenus indicate event handlers that have already been defined. The code for the listener and the empty body of the handler method is generated.

The default name is assigned to the event handler. If multiple events are of the same type, you can use the same handler for all of them. For example, you could set both focusGained and focusLost to use the button1FocusChange handler since they are both of the type java. You can also use the same handler for the same event on multiple components. You can set the code generation style for how the component event code is generated.

Select the event in the property sheet and click the ellipsis Click the Add button and fill out the form. Repeat these steps to add additional event handlers.

Select the unwanted handler and click the Remove button. In the Handlers dialog box, select the unwanted handler and click Remove. When you remove an event handler, the corresponding code block is deleted. If more than one handler uses the same name and same block of code, deleting a single reference to the code does not delete the code itself. You must delete all references to delete the corresponding code block; a confirmation dialog box is displayed first. Guarded text generated includes:.

The initComponents method, in which form initialization is performed. This method is called from the form's constructor and though it is not editable manually, to affect the way it is generated, edit the Code properties in the component's property sheet. The header and trailing brace of all event handlers.

You can modify the way initialization code is generated and even write custom code to be placed within the initialization code. You can modify the way initialization code is generated for a component, form, or component property by editing its Code properties in the Properties window.

In addition, you can write custom code and specify where it should be placed within the initialization code. To modify a form component's guarded block:. Click the Code button at the top of the Properties window to view the Code properties.

Alternatively, you can customize code generated for a component through the Code Customizer dialog box. Select Variable Modifiers and click the ellipsis The Variable Modifiers dialog box opens.

You can edit the access modifiers or other modifiers as needed. The IDE enables form component properties to be initialized in more ways than simply setting static values. A call to a method of the form or one of its components. You can choose from a list of methods that return the appropriate data type. To modify the initialization code for a component's property:.

Click the Properties button at the top of the Properties window. Click the ellipsis Select Form Connection from the Select Mode combo box. If you select Value or User Code, you must add a static value or your custom initialization code in the field provided. You can also place custom code before or after a property's initializer. To do this, follow steps 1 through 4 above, and then click the Advanced button to bring up the Advanced Initialization Code dialog box.

Type your custom pre-initialization code, post-initialization code, or both in the fields provided. This file does not need to be distributed with your application. If you delete this file, you can no longer use the GUI Builder to change the form. You can edit the. Do not modify the content of the initComponents method. The body of this method is always regenerated when the form is opened in the IDE. They are required for the form to open correctly. The multiple document interface MDI model is similar to a traditional computer windowing system in that it includes a desktop above which additional windows float.

In the New File wizard's Project combo box, select the project for which you want to create the form. On the wizard's Name and Location page, enter the form's name in the Class Name combo box, then specify the Location and Package. Click Finish. However, these have standard properties and users can't manipulate them as they might manipulate components in a JInternalFrame container.

To ensure that your GUI forms and the components contained within them meet accessibility requirements, adjust their accessibility properties. A GUI is considered accessible when it works with various assistive technologies, such as screen readers. Accessible Name. Sets the name for the component. By default, the name is set to the component's text property value. Accessible Parent. Sets the name of the accessible parent component.

To edit a form or component's accessibility properties:. In the Navigator window, select the form or component whose accessibility properties you want to modify.

In the Properties window, click the Properties tab and scroll down to the Accessibility properties. Alternately, you can click the current property value to select it and enter a new value. For additional information, see Section To quickly test how your form is displayed when it is compiled and run, click the Test Form button in the GUI Builder toolbar.

A dialog box is displayed with the components arranged as they would actually appear on your form. When you click in a Testing Form dialog box, mouse events are delivered to the actual components and you can see the components "in action. To test your form without compiling and running it:. If you update your form, close any open form Preview windows and click the Preview Design button again to see your changes. Layout managers enable you to control the way in which visual components are arranged in GUI forms by determining the size and position of components within containers.

This is accomplished by implementing the LayoutManager interface. Free Design enables you to lay out your form using visual guidelines that automatically suggest optimal alignment and spacing of components.

As you work, the GUI Builder translates your design decisions into a functional UI without requiring you to specify a layout manager. Because Free Design employs a dynamic layout model, whenever you resize the form or switch locales the GUI adjusts to accommodate your changes without changing the relationships between components. You can combine FreeDesign containers and containers using other layout managers together in the same form.

GroupLayout was added to version 6 of the Java Platform. If you must deploy your application to version 5 of the Java Platform, you must use the version of GroupLayout that is in the Swing Layout Extensions library.

You can set the version of GroupLayout in the property sheet for each form. With the form selected in the Design view, select the form's root node in the Navigator window, and change the Layout Generation Style property. New containers added to forms created in earlier versions of the IDE do not assume the FreeDesign layout manager in order to ensure code compatibility. However, it can be set manually in the Set Layout submenu. You can use other layout managers in the IDE, which might be necessary if you are working with forms created in earlier versions of the IDE, or if you want your form to be compatible with Java Platform version 5 or earlier.

FlowLayout arranges components in a container like words on a page. It fills the top line from left to right until no more components can fit, continuing the same way on each successive line below. BorderLayout arranges components along the edges or the middle of their container. Use BorderLayout to place components in five possible positions: North, South, East, West, and Center corresponding to the container's top, bottom, right and left edges and interior area.

GridLayout places components in a grid of equally sized cells, adding them to the grid from left to right and top to bottom. GridBagLayout is a powerful layout manager that provides precise control over all aspects of the layout even when the container is resized, using a complex set of component properties called "constraints. GridBagLayout places components in a grid of rows and columns in which grid cells do not all have to be the same size.

In addition, components can span multiple rows, columns, or both. For more information about using GridBagLayout see Section CardLayout provides a means of managing two or more components occupying the same display area.

When using CardLayout each component is like a card in a deck, where all cards are the same size and only the top card is visible at any time.

Since the components share the same display space, at design time you must select individual components using the Navigator window. BoxLayout allows multiple components to be arranged either vertically or horizontally, but not both. Components managed by BoxLayout are arranged from left to right or top to bottom in the order they are added to the container. Components in BoxLayout do not wrap to a second row or column when more components are added or even when the container is resized.

Thus a JFrame cannot hold another JFrame. While a JFrame can hold any type of component, typically, a JFrame holds JPanels , which are arranged to group together sets of the components used in the window frame.

The default layout manager of a JFrame is the BorderLayout. A JFrame has a couple of unique and important methods that are worth pointing out:. JApplet -- Allows a Java program to be run as a component in a web page.

Note that an applet and a frame are not the same thing and are not interchangeable, though there are some work-arounds for that which allow the same code to run as either a stand-alone application or an applet in a web page. JPanel -- The basic building block for laying components out in a frame or inside of other panels. The default layout manager for a JPanel is the FlowLayout. JScrollPane -- Allows you to display a single panel with scroll bars on the sides, allowing more or larger components to be displayed than will fit on the screen.

JSplitPane -- Allows two panels to be displayed with either a vertical or horizonatal, user-moveable bar separating them. JTabbedPane -- Allows multiple panels to be displayed in a "tabbed" format. There are overridden forms of this method inherited from java. Container that allow parameters for the layout manager to be passed along, such as specifying the component's position in a BorderLayout. Some layout managers always ignore the size setting of a component because the size is under other constraints..

String getText , void setText String s -- accessor methods for the text of labels, buttons, text fields and text areas.

Graphics --This abstract class is rarely instantiated by the developer's code. A machine-dependent instance of this class is handed to the paintComponent method of a visible GUI component during the screen painting process -- it is NOT instantiated by the developer's code but rather by the Java GUI sub-system. The developer can writed code that will use that supplied Graphics object instance to draw lines, shapes and images onto the screen.

For advanced graphics work, it should be noted that the supplied Graphics object can always be safely downcast to the more capable java. Graphcs2D class. Color -- Represents a color. Has static fields predefined to common colors plus can be expressed in a number of different formats, such as 3-bit RGB values.

Point -- Represents an point on 2-dimensional plane as specified by integer-valued Cartesian coordinates.. Has fields to retrieve the x and y coordinates plus methods for operations such as calculating the distance between two points. For floating point-valued Cartesian coordinates, use the java. Point2D class. Java containers use the Strategy Design Pattern to implement automatic layout management of GUI components on the screen. The management of the size and positions of the contained components is delegated to a "layout manager", which can be set at design time or dynamically changed.

Here are a couple of common layouts:. BorderLayout -- Separates the component into 5 distinct areas, 4 non-resizeable areas on the edges " North ", " East ", " South ", and " West " and one re-sizeable area in the center " Center ". Each area can only contain 1 component, so typically, panels are used in each area to hold multiple components. A typical statement that adds a component to a container that is known to have a BorderLayout installed would be.

FlowLayout -- Holds multiple components in a horizontally arranged line that will wrap around if the width of the container is too small. This GUI init method shall be run in the event-dispatching thread. This warning message is triggered because java. Frame via its superclass java. Component implements the java.

Serializable interface. This interface enables the object to be written out to an output stream serially via method writeObject ; and read back into the program via method readObject. The serialization runtime uses a number called serialVersionUID to ensure that the object read into the program is compatible with the class definition, and not belonging to another version.

Introduction So far, we have covered the basic programming constructs such as variables, data types, decision, loop, array and method and introduced the important concept of Object-Oriented Programming OOP. The java. Custom graphics classes, such as Graphics , Color and Font. They are also called widgets , controls in other graphics systems.

A container can also hold sub-containers. To write a GUI program, we typically start with a subclass extending from java.

Frame to inherit the main window as follows: import java. A Dialog has a title-bar containing an icon, a title and a close button and a content display area, as illustrated. An AWT Applet in package java. Applet is no longer supported in most of the browsers. Secondary Containers: Panel and ScrollPane Secondary containers are placed inside a top-level container or another secondary container.

AWT provides these secondary containers: Panel : a rectangular box used to layout a set of related GUI components in pattern such as grid or flow. Label A java. Note that three static constants Label. LEFT , Label. CENTER are defined in the class for you to specify the alignment rather than asking you to memorize arbitrary integer values. The second constructor constructs a Label object with the given text string in default of left-aligned. The third constructor constructs a Label object with an initially empty string.

You could set the label text via the setText method later. LEFT, Label. Constructing a Component and Adding the Component into a Container Three steps are necessary to create and place a GUI component: Declare the component with an identifier name ; Construct the component by invoking an appropriate constructor via the new operator; Identify the container such as Frame or Panel designed to hold this component. The container can then add this component onto itself via aContainer.

Every container has a add Component method. Take note that it is the container that actively and explicitly adds a component onto itself, NOT the other way.

Button A java. Disabled Button cannot be clicked. Event Clicking a button fires a so-called ActionEvent and triggers a certain programmed action. TextField A java. Each time you click the button, the counter's value increases by 1.

Dissecting the AWTCounter. In other words, this class AWTCounter is a Frame , and inherits all the attributes and behaviors of a Frame , such as the title bar and content pane. Lines 11 to 47 define a constructor, which is used to setup the GUI components and event handlers.

In Line 13, the setLayout inherited from the superclass Frame is used to set the layout of the container. FlowLayout is used which arranges the components in left-to-right and flows into next row in a top-to-bottom manner. A Label , TextField non-editable , and Button are constructed. We invoke the add method inherited from the superclass Frame to add these components into container.

In Line , we invoke the setSize and the setTitle inherited from the superclass Frame to set the initial size and the title of the Frame. The setVisible true method Line 42 is then invoked to show the display. Line is used to setup the callback event-handler, which will be discussed in length later. In brief, whenever the button is clicked, the actionPerformed will be called. In the actionPerformed Lines , the counter value increases by 1 and displayed on the TextField.

The constructor is executed to initialize the GUI components and setup the event-handlers. The GUI program then waits for the user action. For example, if we insert the following code before and after the setvisible : System. Frame Line 6 - the top-level window container. In the constructor Line 14 , we constructs 4 components - 2 anonymous java. Label s and 2 java.

TextField s. The Frame adds the components, in GridLayout. The listener class needs to implement ActionListener interface and provides implementation to method actionPerformed. Callback Methods In the above examples, the method actionPerformed is known as a callback method.

JavaScript can attach a Callback method to an Event Directly In some languages, you can directly attach a method or function to an event such as mouse-click. The sequence of steps is illustrated above: The source object registers its listener s for a certain type of event. The source is triggered by a user. The source create a XxxEvent object, which encapsulates the necessary information about the activation.

For example, the x, y position of the mouse pointer, the text entered, etc. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the appropriate handler on the listener s , which provides the programmed response.

The listener s is required to implement ActionListener interface, and override the actionPerformed method to provide the response. In Line , we write an inner class called BtnCountListener , which override the actionPerformed to increment and display the count. An inner class is a class defined inside an outer class, and it can access the private entities of the outer class. We will elaborate on the inner class in the next section.

The source object registers listener via the addActionListener. The ActionEvent listener is required to implement the ActionListener interface, and override the actionPerformed method to provide the programmed response upon activation. We identify the super Frame as the source object.

It is required to implement the WindowListener interface, which declares 7 abstract methods: windowOpened , windowClosed , windowClosing , windowActivated , windowDeactivated , windowIconified and windowDeiconified. We override the windowClosing handler to terminate the program using System. We ignore the other 6 handlers, but required to provide an empty body for compilation. The sequence diagram is as follow: Example 4: MouseEvent and MouseListener Interface A MouseEvent is fired when you press, release, or click press followed by release a mouse-button left or right button at the source object; or position the mouse-pointer at enter and away exit from the source object.

To demonstrate the MouseEvent : We identity super Frame as the source object. It is required to implement the MouseListener interface, which declares 5 abstract methods: mouseClicked , mousePressed , mouseReleased , mouseEntered , and mouseExit. We override the mouseClicked to display the x, y coordinates of the mouse click on the two displayed TextField s.

We ignore all the other handlers for simplicity - but you need to provide an empty body for compilation. We override the mouseMoved to display the x, y position of the mouse pointer. We ignore the MouseDragged handler by providing an empty body for compilation. Example 6: KeyEvent and KeyListener Interface A KeyEvent is fired when you pressed, released, and typed pressed followed by released a key on the source object. The KeyEvent listener needs to implement the KeyListener interface, which declares 3 abstract methods: keyTyped , keyPressed , keyReleased.

We override the keyTyped to display key typed on the display TextArea. We ignore the keyPressed and keyReleased. An example is as follows: import java.

What are Inner classes? That is, it could contain constructors, member variables and member methods. You can create an instance of a nested class via the new operator and constructor. A nested class is a member of the outer class, just like any member variables and methods defined inside a class.

This is the property that makes inner class useful. A nested class can have private , public , protected , or the default access, just like any member variables and methods defined inside a class.

A private inner class is only accessible by the enclosing outer class, and is not accessible by any other classes. A nested class is NOT a subclass of the outer class. That is, the nested class does not inherit the variables and methods of the outer class.

It is an ordinary self-contained class. The nested class, being defined inside an outer class, can access private members of the outer class. To place a piece of class definition codes closer to where it is going to be used, to make the program clearer and easier to understand.

For namespace management. An anonymous instance of the BtnCountListener inner class is constructed. The btnCount source object adds this instance as a listener, as follows: btnCount. Inner class provides a much cleaner solution! Example 8: An Anonymous Inner Class as Event Listener Instead of using a named inner class called BtnCountListner in the previous example , we shall use an inner class without a name, known as anonymous inner class as the ActionListener in this example. An anonymous instance of an anonymous inner class is constructed, and passed as the argument of the addActionListener method as follows: btnCount.

It is local to the method and cannot be marked with access modifier such as public , private or static , just like any local variable of a method. An anonymous inner class must always extend a superclass or implement an interface.

The keyword " extends " or " implements " is NOT required in its declaration. An anonymous inner class must implement all the abstract methods in the superclass or in the interface. An anonymous inner class always uses the default no-arg constructor from its superclass to create an instance.

If an anonymous inner class implements an interface, it uses the java. Example Using the Same Listener Instance for All the Buttons If you use the same instance as the listener for all the 3 buttons, you need to determine which button has fired the event. Using ActionEvent 's getActionCommand In the following example, we use the same instance of a "named" inner class as the listener for all the 3 buttons.

Downcast back to Button. Layout Managers and Panel A container has a so-called layout manager to arrange its components.

Container public void setLayout LayoutManager mgr To set up the layout of a Container such as Frame , JFrame , Panel , or JPanel , you have to: Construct an instance of the chosen layout object, via new and constructor, e. The Panel container sets to this layout. Container's getLayout method You can get the current layout via Container 's getLayout method.

Accessibility API: provides assistive technology for the disabled. Pluggable look and feel supports.



0コメント

  • 1000 / 1000