0% found this document useful (0 votes)
4 views19 pages

L4 GUI Components - 1

The document discusses various GUI components in Java, focusing on layout management, including FlowLayout and BorderLayout, and how to arrange components within a frame. It explains the model-view-controller architecture and introduces text input components like JTextField and JTextArea, along with their functionalities. Additionally, it provides an example of a simple calculator application and outlines modifications to enhance its functionality.

Uploaded by

KARZAN -t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

L4 GUI Components - 1

The document discusses various GUI components in Java, focusing on layout management, including FlowLayout and BorderLayout, and how to arrange components within a frame. It explains the model-view-controller architecture and introduces text input components like JTextField and JTextArea, along with their functionalities. Additionally, it provides an example of a simple calculator application and outlines modifications to enhance its functionality.

Uploaded by

KARZAN -t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

GUI Components

We have already looked at a few GUI components such as JFrame, JPanel


and JButton. In the next few slides we will see more of them.

But first let’s look at Java’s Layout Management


With layout management one can control how GUI components are arranged
inside a frame. Look back at the program in which we placed three buttons on
a panel. What happens if we add more buttons to that panel? This is what
happens:
As you can see, the buttons are
centered in a row and when there
isn’t more room, then a new row is
started. And if the user resizes the
frame, the buttons will still be centered
in the panel. This is flow layout, the
default layout manager for panels.

Object Oriented Programming in Java 1


GUI Components 2
The flow layout manager lines the components horizontally until there is no
more room and then starts a new row of components. You can choose how
you want to arrange the components in a row; the default is to center them in
the container. You can also align them to the left or to the right:

setLayout(new FlowLayout(FlowLayout.LEFT); //left aligned


setLayout(new FlowLayout(FlowLayout.RIGHT); //right aligned

But except for the simplest programs, flow layout manager is not very
appealing. Another layout manager is called the border layout manager. This
layout manager lets you control choose where you want to place each
component: center, north, south, east or west. For example:
class ButtonPanel extends JPanel{
public ButtonPanel(){
yellowButton=new JButton("Yellow");
blueButton=new JButton("Blue");

Object Oriented Programming in Java 2


GUI Components 3
redButton=new JButton("Red");
orangeButton=new JButton("Oragne");
greenButton=new JButton("Green");
setLayout(new BorderLayout());
add(redButton,"North");
add(yellowButton, "South");
add(blueButton,"East");
add(greenButton, "West");
add(orangeButton, "Center");
}}
But the problem with border layout is that it
grows the components (buttons) so that
they fill all the available space (unlike the
flow layout which preserves the
components’ size.

Object Oriented Programming in Java 3


GUI Components 4
One solution to this is using multiple panels: remember panels are containers
for GUI components and can themselves be arranged inside a larger panel
under the control of a layout manager (We will see more layout managers
later). For example:
class MyFrame extends JFrame{
public MyFrame(){
JPanel panel=new JPanel();
panel.add(yellowButton);
panel.add(redButton);
panel.add(blueButton);
add(panel,“South”);
} //more code
}
Here, a panel is placed at the south of
The frame. (frames have border layout by default)

Object Oriented Programming in Java 4


GUI Components 5
Write a Java application which
will display the following window on
the screen:
The frame (window) has 4 buttons
On the edges of the frame and 12
Buttons in the middle. You can use
Panels and frames for this exercise.
If a button is pressed, the value of
That button should be displayed on
The screen.

Use an array to hold the buttons


in the middle of the frame. Recall
That frames have border layout by
Default. (See next slide)

Object Oriented Programming in Java 5


GUI Components 6
Use the GridLayout manager for the buttons in the middles:
setLayout(new GridLayout(r,c,20,20));
This statement will create an r rows by c columns grid and where the space
(horizontal and vertical) is 20 pixels.

Now back to GUI programming.


Most GUI-based programs consist of three main parts.

1- The GUI itself. This is a front end for the program. It is what the user sees,
containing buttons and other interfaces for the user to provide input, and
various displays for the output.

2- The underlying data. Most programs are ultimately concerned with


manipulating data of some kind, it could be name and address
information, web pages, data recording the state of your simulated city
…etc.

Object Oriented Programming in Java 6


GUI Components 7
3- The code which manipulates the data. This code sits between the GUI and
the data. When the user presses a button, some code might run and perform
some operations on the data, perhaps updating some of the output displays as
a result.

This three-tier program architecture is referred to as the model-view-


controller architecture: the model is the computer representation of the
information being manipulated; the view is the GUI which displays this
data; and the controller is the code which manipulates the data.

In Java two components are used to get text input: text fields and text areas.
Text fields take one line of text only while text areas can take multiple lines of
text. JTextField for text fields and JTextArea for text areas are available in
Java. These two classes have a parent class called JTextComponent. Many
methods are inherited from this class.

Object Oriented Programming in Java 7


GUI Components 8
For example the following three methods are defined in JTextComponent:

void setText(String t); //changes the text of the component


String getText(); //returns the text contained in the component
Void setEditable(boolean); //whether the user can edit the text

TextFields
You can create a new TextField object like this:
JTextField t=new JTextField(20); //20 columns
Or
JTextField t=new JTextField(“Enter text”, 20);//initial value

JLabel class defines labels which can be used to write textual information
inside components. The next example will use JButtons, JTextFields and
JLabels to create a small application that can add two numbers:

Object Oriented Programming in Java 8


GUI Components 9
public class Calcu extends JFrame{
public JButton addB;
private JTextField textField1,textField2, textResult;
private JLabel text1, text2, textLabel;
public Calcu()
{
super("Adding two numbers");

addB=new JButton("Add");
add(addB, "South");

JPanel panel=new JPanel();

textField1=new JTextField(15);
textField2=new JTextField(15);
textResult=new JTextField(18);

Object Oriented Programming in Java 9


GUI Components 10
text1=new JLabel("First Num:");
text2=new JLabel("Second Num:");
textLabel=new JLabel("Result:");
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel.add(text1);
panel.add(textField1);
panel.add(text2);
panel.add(textField2);
panel.add(textLabel);
panel.add(textResult);

add(panel, "Center");
ButtonHandler handler=new ButtonHandler();
addB.addActionListener(handler);
setSize(300,200);
}

Object Oriented Programming in Java 10


GUI Components 11
public static void main(String[] a){
Calcu f=new Calcu();
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setVisible(true); }
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
int num1, num2, result;
num1=Integer.parseInt(textField1.getText().trim());
num2=Integer.parseInt(textField2.getText().trim());
result=num1+num2;
String str=""+ result;
textResult.setText(str.trim());
}
}
}
The program output:

Object Oriented Programming in Java 11


GUI Components 12
The program it now summarized:
The program consists of a frame; inside the frame we create 3 text fields and
three labels to identify the text fields. A button is also created and added to the
bottom section of the frame’s pane. We register this button with a user-defined
listener. We then create a panel and add all the remaining components to it.
The panel is then placed inside the center section of the frame’s pane.

The ButtonHandler which acts as the listener for our button component defines
the actionPerformed method; this method obtains the text fields’ strings and
converts them to integer and then adds the two numbers.

This simple program can add integer numbers only; it cannot even handle
doubles. What’s more, there is no text validation which will cause serious
problems for your program. To make your program robust, you must consider
input validation.

Object Oriented Programming in Java 12


GUI Components 13
58. Change the class Calcu (on slide 9):
a- create two top-level classes (a frame and a panel); the panel will
contain all the components. Event handling should be handled in a
separate class (inner class or separate class)

b- the buttons and labels are arranged more appropriately. Use layout
managements you have seen to achieve this.

c- Also make sure that the Add button at the bottom looks like a button
and does not fill the whole bottom section of the frame.

d- add another button to the frame next to the “Add” button so that when
it is clicked the program is gracefully ended.

e- add yet another button, again next to the previous two, called “Clear”
which will clear the 3 text fields.

Object Oriented Programming in Java 13


GUI Components 14
Swing has another class called JPasswordField which is similar to text fields
except that typed characters inside the field are represented by echo
characters, typically an asterisk (*).

You create a password field like this:


JPasswordField passField(null, 15);

This will create a password field that is 15 columns long (you can store more
than 15 characters inside it). The first parameter is of type String and if
supplied, will set the field to a default password.

To set a different echo character than the asterisk:


Void setEchoCharacter(char echo);

The following method returns the text contained in the password field:
char[] getPassword(); //not a string?

Object Oriented Programming in Java 14


GUI Components 15
Text areas can hold multiple lines of text. JTextArea is used to create text area
components:
JTextArea textArea=new JTextArea(6,60);

This will create a text area 6 lines of 60 columns each. An example follows:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TextAreaFrame extends JFrame implements ActionListener
{ public TextAreaFrame()
{ JPanel p = new JPanel();
insertButton = new JButton("Insert");
p.add(insertButton);
insertButton.addActionListener(this);

Object Oriented Programming in Java 15


GUI Components 16
wrapButton = new JButton("Wrap");
p.add(wrapButton);
wrapButton.addActionListener(this);

noWrapButton = new JButton("No wrap");


p.add(noWrapButton);
noWrapButton.addActionListener(this);

add(p, "South");

textArea = new JTextArea(8, 40);


scrollPane = new JScrollPane(textArea);
add(scrollPane, "Center");

setTitle("TextAreaTest");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

Object Oriented Programming in Java 16


GUI Components 17
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
if (source == insertButton)
textArea.append("This is some text in the
text area component ");
else if (source == wrapButton)
{ textArea.setLineWrap(true);
scrollPane.validate();
}
else if (source == noWrapButton)
{ textArea.setLineWrap(false);
scrollPane.validate();
}
}

Object Oriented Programming in Java 17


GUI Components 18

private JButton insertButton;


private JButton wrapButton;
private JButton noWrapButton;
private JTextArea textArea;
private JScrollPane scrollPane;
}
public class TextAreaTest
{
public static void main(String[] args)
{
JFrame f = new TextAreaFrame();
f.setVisible(true);
}

Object Oriented Programming in Java 18


GUI Components 19
In this example, we first create a JTextArea component; this component lets
you insert multiple lines of text. Then we add 3 buttons: a button to insert
some text into the text area component, another one to wrap long text lines
and a third to disable line wrapping.

Text area components do not have scroll bars. To be able to use scrollable text
you must first create a JScrollPane component and insert the text area object
inside it:
JScrollPane scrollPane;
scrollPane = new JScrollPane(textArea);
Scroll bars automatically appear if there is more text than the textarea can
display.
setLineWrap(true) sets the text area scrollable; setting it to false disables
line wrapping.
Text area components display plain text only; for formatted text you need to
use JEditorPane and JTextPane classes.

Object Oriented Programming in Java 19

You might also like