fbpx

Build an interface graphic in Java ( Java Swing )

The objective of this course is to present some techniques
for building a graphical interface in JAVA.
It is not an exhaustive course, given the complexity of the task.
Java offers 17 packages for interface design graphics, and these packages are among the most complex.
The design of graphical interfaces is therefore complex,and this course aims to give you elements of base that will allow you to go further later.

Graphical API for Java applications

  • Java: a cross-platform language

– the same program must be able to be used in environments
(hardware and OS) different without recompilation.

  • Need to offer an API for independent graphical interfaces it also platforms.
  • The API consists of:

– Java classes and interfaces
-Event management model
-example: a TextField class to define a text input field

 TextField(String content) 
 TextField() 
 void setText(String content) 
 String getText() 
 ...

JAVA API and GUI systems of different Operating systems

  • Problem: GUI Graphical User Interface systems of Operating Systems are very different from each other:
 X Window + motif 
 X Window + gtk 
 MacOS X 
 MS Windows 
 ...
  • Two possible strategies:
  - The JAVA API must make maximum use of the GUI system of the target OS.
  - The JAVA API must make minimal use of the GUI system of the target OS 

Java API for GUI: JAVA AWT

  • Maximum use of the underlying graphics system
- The TextField object delegates most of its tasks to a native component
- The Java programmer uses a TextField object
- The TextField object delegates to an OS-dependent adapter class:
  MotifTextField, GTKTextField, WindowsTextField, MacOSTextField ….
- The native gragic system does most of the work
  • Advantages
the appearance and behavior (look and feel) of Java interfaces identical to
that of "ordinary" applications no need to reimplement components existing
  • disadvantages:
only allows to supply the components available on all platforms difficult to guarantee identical behavior on all platforms

AWT graphics components

The component palette provided by AWT contains only simple components
only standard components existing in all operating systems can be present in AWT

Java API for GUI: JAVA SWING

  • Minimal use of the underlying graphics system
- Use native elements only for basic operations:
  Open a window,
  draw lines / text,
  primitive event management

- Do everything else in Java
 The TextField object is displayed by drawing lines, …

- Advantages:
  ease of avoiding differences between platforms
  any new interface component is immediately
  available on all platforms

- Disadvantages
  need to reimplement all interface components
  Java applications do not have the same look and feel as "ordinary"     applications                 
  slowness?
  • SWING and Java Foundation Classes (IFC)
  • Java Fundation Classes (JFC) launched by SUN in 97 for the creation of graphical interfaces more sophisticated than AWT and integrated since version 2 of Java
  • Swing integrates with JFC
  • JFC = Java 2D API + copy paste inter-applications + Swing + Accessibility
  • Swing:
100% java lightweight components
- Support their display without going through “Peers” objects managed by  the system
 - multiplication of components richer in functionality (tree lists,
 grids….) 
  • Swing Packages

The Swing collection consists of 17 packages. Each package has a separate objective. The most used are:

javax.swing: This is the top level package. It contains the components, adapters, default models of components,… etc.

javax.swing.border: Contains the interfaces and classes that define the different border styles.

javax.swing.colorchooser: Contains the classes for the color choice component.

javax.swing.event: Contains classes and interfaces for types Swing-specific events and listeners. In addition to the event types contained in java.awt.event, Swing components can generate their own event types.

javax.swing.filechooser: Contains classes related to file choice component.

javax.swing.plaf. *: Contains the interfaces and classes that implement the different aspects of the components look-and-feel

javax.swing.table: Swing (PLAF Pluggable Look And Feel). Contains relative interfaces and classes to the table component.

javax.swing.tree: Contains relative interfaces and classes to the tree component.

javax.swing.undo: Contains classes to implement the undo / redo capabilities

Swing component hierarchy

The Swing component hierarchy is divided into two parts
to compare it to that of AWT.

Part 1 of the hierarchy is similar to that of AWT,
However there are twice as many components in Swing than
in AWT.

Part 2 of the hierarchy contains all of the components
Extensive and new swing. This group of components provides
many more properties, and is mainly intended for
professional application developers.

Java Foundation Classes

  • The awt and swing packages are both present in the Java platform
  •   Which package to use: AWT or Swings?
  • There is a third way: SWT (Standard Window ToolKit) developed by IBM – Eclipse
  • similar approach to AWT,
  • much more ambitious, many components, model MVC (Model View Controler)
  • windows, motif, gtk, Mac OS X

Interface development tools

There are interface development tools for Java, but to use them effectively, you need to know how to build the interface manually.

This course aims to teach you how to build a Java interface in two different ways:

Manually, by giving the necessary code to create and manage different components of an interface

By using the NetBeans integrated development environment which contains a tool for building Java interfaces, and then by giving the necessary code for the management of events generated by the various components of the interface.

Creation of a frame

In Java, a high-level window-that is, a window that is not contained in another window – is called frame or framing window).

A frame is represented by the class:
• Frame in the AWT library
• JFrame in the Swing library.

JFrame extends the Frame class

The decoration elements (buttons, title bar, icons, etc.) of a JFrame are not drawn by Swing, but by the user system window system.

Example of a framework creation program

 import javax.swing.*; 
  public class SimpleFrameTest{
  public static void main(String[] args){ 
    SimpleFrame frame = new SimpleFrame();   
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true);              
}
 } 
 class SimpleFrame extends JFrame{
 public SimpleFrame(){
 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 
} 
 public static final int DEFAULT_WIDTH = 300;
 public static final int DEFAULT_HEIGHT = 200; 
} 

The execution of the program produces the framework below:

This frame is completely empty.
Its title bar and its elements, such as the buttons on the right, and the button on the left are drawn by the operating system and not by the Swing library.

If you run the same program on Windows, GTK or Mac, the frills of the frame will be different.
The Swing library draws everything inside the frame.
In this program, it simply fills the frame with a default background color.

Details on the previous program

The program contains the SimpleFrame class which extends the JFrame class.

setSize (): Specifying the size of the frame
By default, a Frame has a size of 0x0 pixels. The SimpleFrame class contains a constructor which modifies the size of the frame and sets them to 300×200 pixels using the setSize () method.

frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE):
End the program when the user closes the frame.

frame.setVisible (true): Displays the frame
Just building a frame doesn’t automatically display it.
Frames are initially invisible, allowing the programmer to add components to them before it is displayed.

Details on the previous program

In each Swing program we have to deal with two technical problems:
1- First, all Swing components must be configured from the event dispatch thread, the thread that transfers events such as mouse clicks and keystrokes on the components. The following code fragment is used to execute instructions in the event dispatch thread:

 EventQueue.invokeLater(
 new Runnable(){
 public void run(){
 instructions 
 } 
 } 
 ); 

2- Next, we must indicate what should happen when the user closes this frame.
In the previous program, we chose to finish the program using the instruction:

frame.setDefaultOperation(JFrame.EXIT_ON_CLOSE);

In other programs containing multiple frames, you don’t will not want to exit the program if the user closes only one of the frames.
By default, a frame is hidden when the user closes it, but the program does not end.

 package jframe; 
 import javax.swing.JFrame; 
 public class Main { 
 public static void main(String[] args) { 
 JFrame frame = new JFrame("Swing"); 
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 // Set the x, y, width and height properties 
 frame.setBounds(50, 50, 200, 200); 
 frame.setVisible(true); 
 }
 } 
 package jframe;
 import java.awt.Container;
 import javax.swing.JButton;
 import javax.swing.JFrame; 
 public class Main2 { 
  public static void main(String[] args) {
   JFrame frame = new JFrame("JFrame"); 
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
   Container contentPane = frame.getContentPane(); 
 
 // Add a close button 
   JButton closeButton = new JButton("Close");
   contentPane.add(closeButton); 
 // set the size of the frame 300 x 200 
   frame.setBounds(50, 50, 300, 200);
   frame.setVisible(true); 
 } 
} 
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main3 {
public static void main(String[] args) {
JFrame frame = new JFrame(“JFrame”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add a close button
JButton closeButton = new JButton(“Close”);
Container contentPane = frame.getContentPane();
contentPane.add(closeButton);
// Calculates and sets appropriate size for the frame
frame.pack();
frame.setVisible(true);
}
}

Threads in a GUI program

When the main function ends, it does not end the program, but simply the main thread.

The event dispatch thread keeps the program active until its completion, either by closing the frame or by calling the System.exit (); method

Positioning of a frame

The Jframe class provides only a few methods capable of modifying the appearance of a frame.

However, thanks to inheritance, the various JFrame superclasses offer most of the methods for influencing the size and position of a frame.

It is generally in the Component class (ancestor of all GUI objects) or in the Window class (superclass of the parent of the Frame class) that we look for methods that allow us to modify the size and position of the frames.

For example, the setLocation () method which allows you to reposition a component is found in the Component class.

JFrame class inheritance hierarchy

Important methods of positioning a frame

void setLocation (int x, int y): java.awt.Component Moves the component to a new location. The x, y coordinates use the container coordinates if the component is not high level or the screen coordinates if the component is high level (for example, a Jframe).
The upper left corner of the component is placed at x pixel from the left edge and y pixel from the top edge of the container (screen in case the component is a frame)

void setBounds (int x, int y, int width, int height): java.awt. Component moves and resizes the component.

Void setLocationByPlatform (boolean b): java.awt.Windows Sets the locationPlatform property. When this property is set to true
before the frame is displayed, the platform window system chooses
the location of the frame, usually with a slight offset from the last window.

boolean isLocationByPlatform (): java.awt.Window
Gets the LocationByPlarform property.

void setTitle (String s): java.awt.Frame
Sets the title property which determines the text in the title bar of the frame.

String getTitle (): java.awt.Frame
Gets the title property of the frame.

void setVisible (boolean b): java.awt.Component
Sets the visible property. Originally, the components are visible, with the exception of high-level components like Jframe.

boolean isVisible (): java.awt.Component
Gets the visible property of the frame.

void setIconImage (Image image): java.awt.Frame
Sets the iconImage property which determines the frame icon.

GetIconImage Image: java.awt.Frame
Gets the iconImage property of the frame.

void setSize (int width, int height): java.awt.Component
Resizes the component by giving it the specified width and height.

Void setResizable (boolean b): java.awt.Frame
Sets the resizable property. When setting Resizable to true, the user can change the size of the frame.

Boolean isResizable (): java.awt.Frame
Gets the value of the resizable property.

Void toFront (): java.awt.Window
Displays this window above all others.

Void toBack (): java.awt.Window
Place this window on top of the stack of desktop windows and rearrange the other visible windows.

Boolean isUndecorated (): java.awt.Frame
Void setUndecorated (boolean b): java.awt.Frame

Retrieve or set the undecorated property. When the property is set to true, the frame is displayed without decoration. This method must be called before the frame is displayed.

int getExtendedState (): java.awt.Frame
Void setExtendedState (int state): java.awt.Frame

Retrieve or set the extended state of the window. The state is one of these:
Frame.NORMAL
Frame.ICONIFIED
Frame.MAXIMIZED_HORIZ
Frame.MAXIMIZED_VERT
Frame.MAXIMIZED_BOTH

Static Toolkit getDefaultToolkit (): java.awt.Toolkit
Returns the default toolbox

GetScreenSize () dimension: java.awt.Toolkit
Get the screen size

GetImage image (String filename): java.awt.Toolkit
Loads an image from the file specified by filename.

Determine an appropriate frame size
depending on the screen size

To simplify our previous program, we gave the frame a size that should be accepted by most display systems.

However, in a professional application, you must first determine the screen resolution in order to adjust the size of the frame.

A window that may appear reasonably large on a laptop screen will be the size of a postage stamp on a high-resolution screen.

To know the size of the screen, proceed to the following steps:
• Call the static method getDefaultToolkit of the Toolkit class to obtain the Toolkit object (the Toolkit class is a dumping ground for various methods which interface with the native windowing system).
• Then call the getScreenSize method, which returns the size of the screen as a Dimension object (a Dimension object simultaneously stores a width and a height in public instance variables called width and height respectively

The code is therefore:

Toolkit kit = Toolkit.getDefaulTooltkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
Int screenHeight = screenSize.height;
setSize(screenWidth/2, screenHeight/2);
setLocationByPlatform(true);
Image img = kit.getImage(« icône.gih »);
setIconImage();

The full program is provided on the next page

Displaying information in a component

In what follows, we will see how to display text in a frame as shown in the diagram below.

It is possible to draw the message directly in the frame, but this is not considered a good programming technique.

In Java, frames are designed to be Containers of other components (menu bars, and other components).

We normally draw on another component previously added to the frame.

Internal structure of a JFrame

The structure of a frame is very complex, it has 4 layers:
Root Pane: Jroot
Layered Pane: JLayeredPane
Content pane
Glass pane

Only the ContentPane part is used in Swing programming,

the other layers are necessary for the organization of the menu bar and the content, as well as to implement the Look and Feel aspect of the frame.

When we design a frame, we add components to the ContentPane using instructions like these:

Since Java SE 5.0, you can simply write the instruction:

which does the same job as the instructions above

In our case, we only want to add to the content a component on which we will write the message.

To draw on a component, you define a class that extends the JComponent class and replaces the paintComponent method in this class.

The paintComponent method receives a parameter, of type Graphics

A Graphics object stores a set of parameters, such as font and color, and has methods for drawing patterns, images, and text.

To create a panel you can draw on, use the instructions below.

Each time a window must be redrawn, for whatever reason (modification of its size, its reopening after having reduced it on the taskbar, etc.), the event handler sends a notification to the component .

The paintComponent methods of all components are then automatically executed.

Never call the paintComponent method directly. It is called automatically when a portion of your frame needs to be redrawn; you should not create interference.

If you need to force a window to redraw, call the repaint method rather than paintComponent.

The repaint method calls paintComponent for all components of the window, each time providing an appropriate Graphics object.

The paintComponent method takes a single parameter of type Graphics.

The coordinates and dimensions applied to a Graphics object are expressed in pixels.

The coordinates (0,0) represent the upper left corner of the component on which you are drawing.

Text display is considered a special form of drawing.
The Graphics class has a drawString method whose syntax is:
g.drawString (text, x, y);

We want to draw the string “Not a hello, World program” roughly in the center of the original window. So we will make it start at position (75, 100). This means that the first character will be located 75 pixels from the left edge and 100 pixels from the upper edge of the window.

Instead of extending JComponent, we prefer to extend the JPanel class.
A JPanel is intended to be a container of other components, but it is also possible to draw on it.

/** *
A panel that displays a message.
*/
class NotHelloWorldPanel extends JPanel{
public void paintComponent(Graphics g) {
g.drawString(“Not a Hello, World program” , MESSAGE_X, MESSAGE_Y);
}
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
}
/** * A frame that contains a message board */

class NotHelloWorldFrame extends JFrame {
public NotHelloWorldFrame() {
setTitle(“NotHelloWorld”);
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add the panel to the frame

NotHelloWorldPanel panel = new NotHelloWorldPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

Introduction to Swing

basic components
containers
Windows
placement of components (layout managers)
interaction management (events)

Structure of the graphical interface

The creation of the graphical interface necessarily goes through an instance of the Jframe class

From the operating system point of view this window represents
the application

The window plays the role of “container” in which the various constituent elements (components) of the graphical interface of the application will be arranged (buttons, drop-down lists, input area, etc.)

these items referred to as

  • controls (HMI)
  • components (components in JAVA)
  • widgets (Xwindow-Motif)

JLabel component

Use :
♦ display static text and / or an image
♦ Does not react to user interactions

Definition of label text
♦ In the constructor JLabel lb = new JLabel (“a label”);
♦ Using the setText method
lb.setText (“another text for the label”);
♦ Symmetrical method lb.getText ()

Definition of an icon:
♦ By default no image
♦ In the constructor: Jlabel (Icon icon)
By the setIcon method: lb.setIcon (new ImageIcon (“info.gif”);

Specifying the position of the text relative to the icon
lb.setVerticalTextPosition (SwingConstants.BOTTOM);
lb.setHorizontalTextPosition (SwingConstants.CENTER);

Text formatting:
setText supports HTML: lb.setText (” this text is in Bold “)
attention: if incorrect HTML text, exception thrown at runtime

JTextField component

Examples of Creating a JTextField
♦ JTextField jtf = new JTextField ();
♦ JTextField jtf = new JTextField (“a text”);
♦ JTextField jtf = new JTextField (20);

Text modification
♦ By user interaction
♦ jtf.setText (“the text”);

Recover text
♦ jtf.getText ();

Copy paste
♦ jtf.copy () or jtf.cut ()
♦ jtf.paste ();

Prohibit seizure
♦ jtf.setEditable (false);

JTextField component

A JTextField can handle a line of text.
Its builders can receive a combination of three values below:

A string – specifies the initial text. The default value is null.

The number of columns – specifies the width. The default value is 0.

A Document object – specifies the model.

The Document model is an instance of the PlainDocument class.
The table on the next slide lists the constructors of the JTextField class.

JTextField Text alignment

By default, the text is left aligned.
To align the text inside a JTextField, use the method :

public void setHorizontalAlignment (int alignment)
Who takes the arguments below

  • JTextField.LEFT
  • JTextField.CENTER
  • JTextField.RIGHT
  • JTextField.LEADING (the default)
  • JTextField.TRAILING

2 thoughts on “Build an interface graphic in Java ( Java Swing )

  1. Greetings from Colorado! I’m bored to tears at
    work so I decided to check out your blog on my iphone during lunch break.
    I love the information you present here and can’t wait to
    take a look when I get home. I’m amazed at
    how fast your blog loaded on my cell phone .. I’m not even using
    WIFI, just 3G .. Anyways, awesome blog!

Leave a Reply

Your email address will not be published. Required fields are marked *