0% found this document useful (0 votes)
8 views

Attachment

Uploaded by

ewakjira5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Attachment

Uploaded by

ewakjira5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

3/20/2024 Java programming 1

Chapter 3: Java GUI using JAVAFX


 3.1. JAVAFX architecture and Program structure
 3.2. JAVAFX layout components
 3.3. Basic UI controls
 3.3.1. Event handlers
 3.3.1. UI controls
 3.4. Composite UI controls
 3.5. Shapes
 3.5.1. Color, Texts, Fonts
 3.5.2. Lines, Circle, Rectangle
 3.5.3. CSS styling
 3.6. Properties and Bindings
 3.7. Graphics and Animation
3/20/202
Java Programming 2
4
Graphical User Interface (GUI)
oPresents a user-friendly mechanism for interacting with an application.
oPronounced as “GOO-ee”
oGives an application a distinctive “look and feel.”
oAre built from GUI components.
oThese components are sometimes called controls or widgets(window
gadgets).
oA GUI component is an object with which the user interacts via the
mouse, the keyboard or another form of input, such as voice recognition.

3/20/2024 Java Programming 3


Cont….. GUI
Together, the appearance and how user interacts with the
program are known as the program "look and feel".
The classes that are used to create GUI components are part
of the java.awt or javax.swing package.
Both these packages provide rich set of user interface
components.
Most applications you use on a daily basis use windows or dialog
boxes (also called dialogs) to interact with the user.
oFor example: e-mail programs allow you to type and
read messages in a window provided by the e-mail
program.

3/20/202
Java Programming 4
4
Cont….. GUI
o Typically, dialog boxes are windows in which programs display
important messages to the user or obtain information from the user.
oJava’s JOptionPane class (package javax.swing) provides
prepackaged dialog boxes for both input and output.
oThese dialogs are displayed by invoking static JOptionPane
methods.

3/20/202
Java Programming 5
4
Cont….. GUI
When Java was first released in 1995, it contained a GUI API referred to as
the Abstract Window Toolkit (AWT).
The classes and interfaces of the AWT are in the java.awt package.
Aware of the need for a more robust API for creating GUI applications, Sun
Microsystems teamed together with Netscape (and other industry partners)
then created Swing package.
Actually there are two sets of GUI components in Java.
AWT and
Swing

3/20/202
Java Programming 6
4
Cont….. GUI
 Swing is asset of classes that provides more powerful and flexible components than
are possible with the AWT.
 The classes and interfaces of Swing are found in the javax.swing package.
 The names of the Swing classes all begin with a capital "J" , like JButton, JLabel,
JFrame.
 For the most part, an AWT program can be converted to a Swing program by adding a
capital J to the class names used in the source code and recompiling the code.

3/20/202
Java Programming 7
4
Swing vs. AWT
Swing AWT
oOperating system independent Operating system dependent
oLightweight Heavyweight
oBase on Write once use anywhere Not consistent as compared to Swing
oFeel and look Change behavior due to operating system
oRich set of object Less as compared

3/20/202
Java Programming 8
4
JavaFx Components
 Jlabel
 Displays un editable text or icons.
 JTextField
 Enables user to enter data from the keyboard.
 Can also be used to display editable or un editable text.
 JButton
 Triggers an event when clicked with the mouse.
 JCheckBox
 Specifies an option that can be selected or not selected.
 JComboBox
 Provides a drop-down list of items from which the user can make a selection by clicking an item or
possibly by typing into the box.
 Jlist
 Provides a list of items from which the user can make a selection by clicking on any item in the list.
Multiple elements can be selected.
 Jpanel
 Provides an area in which components can be placed and organized. Can also be used as a drawing
area for graphics

3/20/2024 Java Programming 9


JLabel

 To create a label, use the JLabel class.


 A label is a display area for a short text, an image, or both.
 It is often used to label other components (usually text fields).

3/20/202
Java Programming 10
4
Jlabel constructors
 public JLabel() // label with no text or icon
 public JLabel(icon: javax.swing.Icon) // with icon
 public JLabel(icon: Icon, hAlignment: int)
 Creates a label with an icon and the specified horizontal alignment.

 public JLabel(text: String) // label with a text


 public JLabel(text: String, icon: Icon, hAlignment: int)
 public JLabel(text: String, hAlignment: int)
3/20/202
Java Programming 11
4
JTextField
 A text field can be used to enter or display a string.
 JTextField is a subclass of JTextComponent.
 Text fields are objects belonging to the class JTextField.
 Therefore, you can create a text field by declaring a reference
variable of type JTextField followed by an instantiation of the
object.

3/20/202
Java Programming 12
4
Some Methods of the class JTextField
 public JTextField(int columns)
 Creates an empty text field with a specified number of columns.

 public JTextField(String str)


 Creates a text field initialized with the specified text.

 public JTextField(String str, int columns)


 Creates a text field initialized with the specified text and columns.

 public void setText(String str)// To set new text in a text field


 public String getText()// To get the text from a text field
 public void setEditable(boolean b)
 public void addActionListener(ActionListener obj)
3/20/202
Java Programming 13
4
JButton
 A provides button is a component that triggers an action when clicked.
 Swing regular buttons, toggle buttons, check box buttons, and radio buttons.
 The common features of these buttons are defined in
javax.swing.AbstractButton,
 JButton inherits AbstractButton and provides several constructors to create
buttons.

3/20/202
Java Programming 14
4
JButton constructors
 public JButton()
 Creates a default button without any text or icons.
 public JButton(icon: javax.swing.Icon)
 Creates a button with an icon.
 public JButton(text: String)
 Creates a button with text.
 public JButton(text: String, icon: Icon)
 Creates a button with text and an icon.

3/20/202
Java Programming 15
4
JCheckBox
oTo create a check box button, use the JCheckBox class.
oA toggle button is a two-state button like a light switch. JToggleButton inherits
AbstractButton and implements a toggle button.
oOften JToggleButton’ssubclasses JCheckBox and JRadioButton are used to enable the
user to toggle a choice on or off.
oJCheckBox inherits all the properties from AbstractButton, such as text, icon, mnemonic,
vertical Alignment, horizontal Alignment, horizontal Text Position, verticalTextPosition,
and selected, and provides several constructors to create check boxes.

3/20/202
Java Programming 16
4
JCheckBox constructors
opublic JCheckBox()
Creates a default check box without any text or icon.
o public JCheckBox(text: String)//Creates a check box with text.
opublic JCheckBox(text: String, selected: boolean)
Creates a check box with text and specifies whether the check box is
initially selected.
opublic JCheckBox(icon: Icon)
Creates a check box with an icon
opublic JCheckBox(text: String, icon: Icon)
Creates a check box with text and an icon.
opublic JCheckBox(text: String, icon: Icon, selected: Boolean)

3/20/202
Java Programming 17
4
Cont’d
oHere is an example for creating a check box with the text Student. Its foreground is red,
the background is orange, its mnemonic key is S, and it is initially selected.
JCheckBox jchk = new JCheckBox("Student", true);
jchk.setForeground(Color.RED);
jchk.setBackground(Color.ORANGE);
jchk.setMnemonic('S');

oThe button can also be accessed by using the keyboard mnemonics. Pressing Alt+S is
equivalent to clicking the check box.
oTo see if a check box is selected, use the is Selected() method.

3/20/202
Java Programming 18
4
JRadioButton
oTo create a radio button, use the JRadioButton class.
oRadio buttons, also known as option buttons, enable you to choose a single item from a
group of choices.
oInherits AbstractButton and provides several constructors to create radio buttons,
oThese constructors are similar to the constructors for JCheckBox.

3/20/202
Java Programming 19
4
Cont’d
oHere is an example for creating a radio button with the text Student.
oThe code specifies black foreground, white background, mnemonic key S,
and initially selected.
JRadioButton jrb = new JRadioButton("Student", true);
jrb.setForeground(Color.BLACK);
jrb.setBackground(Color.WHITE);
jrb.setMnemonic('S');

3/20/202
Java Programming 20
4
JComboBox
o Provides a list of items from which the user can make a single selection.
o They generate Item Events
o Each item in a JComboBox has an index.
o The first item added to it appears as the currently selected item when the
JComboBox is displayed.
o Other items are selected by clicking the JComboBox, which expands into a list from
which the user can make a selection.
o Method setMaximumRowCount sets the maximum number of elements that are
displayed when the user clicks the JComboBox.
o If there are additional items, the JComboBox provides a scrollbar that allows the user
to scroll through all the elements in the list.

3/20/202
Java Programming 21
4
JList
 A JList displays a series of items from which the user may select one or more items.
 Class JList supports single-selection lists and multiple-selection lists.
 JList method setVisibleRowCount specifies the number of items that are visible in
the list.
 JList method setSelectionMode specifies a list’s selection mode.
 A JList does not provide a scrollbar if there are more items in the list than the
number of visible rows.
 In this case, a JScrollPane object can be used to provide the scrolling capability.

3/20/202
Java Programming 22
4
JList properties
 After creating a JList component, you can modify each of its many properties.
 Basically, many of the JList properties are related to the process of selection.
 Selected Value: relate to the contents of the selected item.
It works only when a single item is selected in the list.
When multiple items are selected, it is simply the value for the smallest selected
index.
If you want to deal with multiple selected items in all then you can use the selected
Values property.
Both properties has getter and setter methods.

3/20/202
Java Programming 23
4
Syntax
jlist.getSelectedValue();
jlist.setSelectedValue(Object); //for a single item
jlist.getSelectedValues();
jlist.setSelectedValues(Object[]); //multiple items
 selectedIndex
o The items in the JList object will have an integer value called index.
o The first item in the list will have an index value of 0; while the last item
will obtain an index value of n-1 where n is the total number of items in the
JList object.
 JList has a property called selectedIndex that help you deal with the index of
an item.

3/20/202
Java Programming 24
4
Cont’d
import java.awt.*;
import javax.swing.*;
public class test5 {
public static void main(String args[]){
JFrame listFrame = new JFrame("Swing JList");
String listLabels[] = {"Advanced Programming","Internet Programming","Compiler
Design","Complexity Theory","OOSAD","Elective 1"};
JList courses = new JList(listLabels);
JScrollPane listScroll = new JScrollPane(courses);
courses.setVisibleRowCount(4);
courses.setSelectedIndex(2);
listFrame.setLayout(new FlowLayout());
listFrame.add(listScroll);
listFrame.setVisible(true);
listFrame.setSize(300,200);
listFrame.setResizable(false);
listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
3/20/202
Java Programming 25
4
How to build a GUI
oCreate a window in which to display things—usually a JFrame (for an
application).
oUse the setLayout(LayoutManager manager) method to specify a layout
manager
 A Frame is a window for holding other GUI components.
 To create a user interface, you need to create either a frame or an applet
to hold the user interface.
 JFrame provides the basic attributes and behaviors of a window—a
title bar at the top of the window, and buttons to minimize , maximize
and close the window.

3/20/202
Java Programming 26
4
Cont’d
oTo create a frame, use the JFrame class
oThe class JFrame provides various methods to control the attributes of a
window.
oFor example, it has methods to set the window title and methods to specify
the height and width of the window.
oPublic JFrame()
This is used when an object of type JFrame is
instantiated and the window is created without any title.
Example: JFrame myWindow = new JFrame();
myWindow is a window with no title

3/20/202
Java Programming 27
4
Cont’d
 Public JFrame(String s)
o Creates a frame with the specified title.
oExample: JFrame myWindow = new JFrame("Rectangle");
omyWindow is a window with the title Rectangle
 Public void setSize(int w, int h)
o Method to set the size of the window.
 Example: myWindow.setSize(200 , 125);
 Public void setVisible(boolean b)
o Method to display the window in the program. If the value of b is true, the window will be displayed on
the screen.
oExample: myWindow.setVisible(true);

3/20/202
Java Programming 28
4
Cont’d
 Public void setDefaultCloseOperation(int operation)
o Method to determine the action to be taken when the user clicks on the window closing button to
close the window.
o Choices for the parameter operation are the named constants
 EXIT_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, and
DO_NOTHING_ON_CLOSE.
oExample: setDefaultCloseOperation(EXIT_ON_CLOSE);
Public void addWindowListener(WindowEvent e)
oMethod to register a window listener object to a JFrame.
oThe class JFrame also contains methods to set the color of a window.

3/20/202
Java Programming 29
4
Cont’d
oThe program to create the window uses the class JFrame; this class is contained
in the package javax.swing.
oTherefore, the program must include either of the following two statements:
import javax.swing.*;
or
import javax.swing. JFrame;
oUsing the add method, you can add components to the frame.
Example:
JFrame frame = new JFrame();
JButton jbtOK=new JButton("OK");
frame.add(jbtOK);

3/20/202
Java Programming 30
4
Layout Managers
oLayouts allow you to format components on the screen in a platform-independent
way.
oEach container contains a layout manager, which is an object responsible for
laying out the GUI components in the container.
oThe Java GUI components are placed in containers, where they are arranged by the
container’s layout manager.

3/20/202
Java Programming 31
4
Cont…..
The standard JDK provides many classes that implement
the Layout Manager interface, including:
o Flow Layout
o Grid Layout
o Border Layout
A layout manager is created using a layout manager class.
Layout managers are set in containers using the
setLayout(aLayoutManager) method.
For example, you can use the following statements to
create an instance of XLayout and set it in a container:
LayoutManager lManager = new XLayout();
container.setLayout(lManager);
3/20/202
Java Programming 32
4
Flow Layout
Flow Layout
oIs the simplest layout manager.
oIt add components to the screen, they flow left to right
(centered) based on the order added and the width of the
screen.
oVery similar to word wrap and full justification on a
word processor.
oIf the screen is resized, the components' flow will
change based on the new width and height
oIs the default layout for the JPanel class.
 public FlowLayout()
oCreates a new object that centers the components with a horizontal and vertical gap of 5 units.

3/20/202
Java Programming 33
4
Cont’d
o Public FlowLayout(int align):
o Creates a new object with one of specified alignment:
 FlowLayout.CENTER,

 FlowLayout.RIGHT, or

 FlowLayout.LEFT.

o Public FlowLayout(int align, int hgap, int vgap):


o Creates a FlowLayout object with the specified alignment,
horizontal gap, and vertical gap.

3/20/202
Java Programming 34
4
Cont’d
Example
import javax.swing.*;
import java.awt.*;
public class ShowFlowLayout {
public static void main( String args[] ) {
JFrame frame = new JFrame( "My First GUI Program" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLayout( new FlowLayout() );
for ( int i = 0; i < 10; i++ ) {
frame.add( new JButton( String.valueOf( i ) ) );
}
frame.setSize(400,300); Output:
frame.setVisible(true);
}} // ShowFlowLayout

3/20/202
Java Programming 35
4
Grid Layout
Arranges components in rows and columns
oIf the number of rows is specified
Columns = number of components / Rows
oIf the number of columns is specified
Rows = number of components / Columns
oThe number of columns is ignored unless the number of rows is zero.
The order in which you add components matters
oComponent 1  (0,0), Component 2  (0,1),
oComponents are resized to fit the row-column area

3/20/202
Java Programming 36
4
Cont’d
oPublic GridLayout(int rows, int cols):
Creates new object with the specified number of rows and columns. The horizontal and vertical gap
between components is zero unit.
o Public GridLayout(int rows, int cols, int hgap, int vgap):
Creates new object with the specified number of rows and columns and
also with the specified horizontal and vertical gap.
o public GridLayout():
Creates a default GridLayout manager.

3/20/202
Java Programming 37
4
Border Layout
oThe BorderLayout manager divides a container into five areas:
East, South, West, North, and Center.
oWhen a Component is added to the layout, you must specify which
area to place it in.
oThe center area will always be resized to be as large as possible.
oOnly one component can be added to a given region, and the size
of the component is determined by the region it appears in.

3/20/202
Java Programming 38
4
Events and Event Handling
o In Swing Components, you worked with ActionEvents and
ItemEvents that are generated when a user works with a control that is
included in one of your programs.
oThe parent class for all events is EventObject, which descends from
the Object class.
oEventObject is the parent of AWTEvent, which in turn is the parent
of specific event classes such as ActionEvent and ItemEvent.
oThe abstract class AWTEvent is contained in the package
java.awt.event.

3/20/202
Java Programming 39
4
Cont’d
oActionEvents are generated by components that users can click, such
as JButtons, and
oTextEvents are generated by components into which the user enters
text, such as JTextFields.
oMouseEvents include clicking a component, and you can select
information from a MouseEvent such as determining the location of
the mouse pointer and distinguishing between a single- and double-
click

3/20/202
Java Programming 40
4
Cont’d

User Action oResulting Event Type


Click a button oActionEvent
Click a component oMouseEvent
Click an item in a list box oItemEvent
Click an item in a check box oItemEvent
Change text in a text field oTextEvent
Open a window oWindowEvent
 Iconify a window oWindowEvent
Press a key oKeyEvent

3/20/202
Java Programming 41
4
Using Menus
oMenus are lists of user options; they are commonly added features in
GUI programs.
oApplication users are accustomed to seeing horizontal menu bars
across the tops of frames, and they expect to be able to click those
options to produce drop-down lists that display more choices.
oThe horizontal list of JMenus is aJMenuBar.
oEach JMenu can contain options, called JMenuItems, or can contain
submenus that also are JMenus.

3/20/202
Java Programming 42
4
Con’t
oFor example, the following figure shows a JFrame that illustrates the use of the
following components: Fig-1

3/20/202
Java Programming 43
4
Cont’d
To create the output shown in Fig-1, a series of JMenuBar, JMenu,
and JMenuItem objects were created and put together in stages.
You can create each of the components you see in the menus in Fig-1
as follows:
o You can create a JMenuBar much like other objects—by using the new
operator and a call to the constructor, as follows:
JMenuBar mainBar = new JMenuBar();
oYou can create the two JMenus that are part of the JMenuBar:
JMenu menu1 = new JMenu("File");
JMenu menu2 = new JMenu("Colors");

3/20/202
Java Programming 44
4
Cont’d
oThe three components within the Colors JMenu are created as follows:
JMenu bright = new JMenu("Bright");
JMenuItem dark = new JMenuItem("Dark");
JMenuItem white = new JMenuItem("White");
oThe two JMenuItems that are part of the Bright JMenu are created as follows:
JMenuItem pink = new JMenuItem("Pink");
JMenuItem yellow = new JMenuItem("Yellow");
oOnce all the components are created, you assemble them.
o You add the JMenuBar to a JFrame using the setJMenuBar() method as follows:
setJMenuBar(mainBar);

3/20/202
Java Programming 45
4
Cont’d
oUsing the setJMenuBar() method assures that the menu bar is
anchored to the top of the frame and looks like a conventional menu
bar.
oNotice that the JMenuBar is not added to a JFrame’s content pane; it
is added to the JFrame itself.
o The JMenus are added to the JMenuBar using the add() method. For
example:
mainBar.add(menu1);
mainBar.add(menu2);

3/20/202
Java Programming 46
4
Cont’d
oA submenu and two JMenuItems are added to the Colors menu as
follows:
menu2.add(bright);
menu2.add(dark);
menu2.add(white);
oA submenu can contain its own JMenuItems.
oFor example, the Bright JMenu that is part of the Colors menu in Fig-1 contains its
own two JMenuItem objects:
bright.add(pink);
bright.add(yellow);

3/20/202
Java Programming 47
4
JavaFX shapes
JavaFX provides set of 2D classes for defining and performing operations on objects
related to two-dimensional geometry.
❑ Using the JavaFX library, you can draw:
❑ Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline,
Cubic Curve, Quad Curve, Arc.
❑ Path elements such as Line, Horizontal Line, Vertical Line, Cubic Curve,
Quadratic Curve, Arc.
❑ In addition to these, you can also draw a 2D shape by parsing SVG path.
❑ Each of the above mentioned 2D shape is represented by a class and all these
classes belongs to the package javafx.scene.shape

3/20/202
Java Programming 48
4
Creating a Shape
 To create a shape, you need to :
 Instantiate the respective class of the required shape.
 Set the properties of the shape.
 Add the shape object to the root node(parent node).

3/20/202
Java Programming 49
4
JavaFX CSS styling
JavaFX provides the facility to configure the theme of the application.
❑ JavaFX provides the package javafx.css which contains all the classes.
❑ Applying CSS to the JavaFX application is similar to applying CSS to the
HTML page.
❑ JavaFX caspian.css file as default CSS stylesheet

3/20/2024 Java Programming 50


JavaFX properties and binding
❑ JavaFX properties store the inner state of a control and allow us to listen to
state change from JavaFX UI controls.
❑ JavaFX Properties can be bound to one another.
❑ Binding allows properties to synchronize their values based on a changed
value from another property.
❑ To bind a property to another property, call the bind().
Example
TextFielduserInput= new TextField();
Labellabel= new Label();
label.textProperty().bind (userInput.textProperty());

3/20/202
Java Programming 51
4
JavaFX Animation
❑ Animation is a transition that gives an object the illusion of motion.
❑ A node can be animated by changing its property over time.
❑ javafx.animationcontains classes that are used to animate the nodes.
❑ Animation is the base class of all these classes.
❑ We can apply animations (transitions) such as Fade Transition, Fill Transition,
Rotate Transition etc.
 To apply a particular animation to a node, you have to follow the steps given
below:
 ❑Create a required node using respective class.
 ❑Instantiate the respective transition (animation) class that is to be applied
 ❑Set the properties of the transition and
 ❑Finally play the transition using the play() method of the Animation class.

3/20/202
Java Programming 52
4
JavaFX Animation Example
Rectangle rt =newRectangle(136,112,112,112);
rt.setFill(Color.YELLOW);
RotateTransition r =newRotateTransition();
r.setDuration(Duration.millis(2000));
r.setAxis(Rotate.Y_Axis);
r.setCycleCount(600);
r.setnode(rt);
r.play();

3/20/202
Java Programming 53
4
THE END OF CHAPTE THREE

3/20/2024 Java Programming 54

You might also like