Title: TCU CoSc 10403 Introduction to Programming with Java
1TCU CoSc 10403 Introduction to Programming (with
Java)
2Components
- GUI components (widgets) are defined in the Java
API and are used to provide mechanisms that allow
a user to interact with an applet. (GUIs) - Widgets are the parts that are used to build
graphical user interfaces (e.g. buttons, menus,
text areas, etc). - There are two libraries of enhanced graphics
components that are available to Java
programmers - AWT - abstract window toolkit (may have a
different appearance on different platforms) - Swing a more modern widget toolkit developed
to provide a more sophisticated set of GUI
components. (should look the same across
different platforms)
3Visual Guide to Java Swing Components
Borrowed from http//java.sun.com/docs/books/tut
orial/ui/features/components.html
4Swing vs. AWT
- Swing is built on top of AWT, so you need to
import AWT and use a few things from it - Swing is bigger and slower
- Swing is more flexible and better looking
- Swing and AWT are incompatible--you can use
either, but you cant mix them - Actually, you can, but its tricky and not worth
doing - Basic controls are practically the same in both
- AWT Button b new Button ("OK")
- Swing JButton b new JButton("OK")
- Swing gives far more options for everything
(buttons with pictures on them, etc.)
5To build a GUI...
- Make somewhere to display things (a Container)
- Usually you would use a JFrame or a JApplet
- Create some Components (buttons, text areas,
panels, etc.) - Its usually best to declare Components as
instance variables, and - Define them in your applets init() method or in
some application method - Add your Components to your display area
- Choose a layout manager
- Add your Components to your JFrame or JApplet
according to the rules for your layout manager - Attach Listeners to your Components
- Interacting with a Component causes an Event to
occur - A Listener gets a message when an interesting
event occurs, and executes some code to deal with
it
6Containers and Components
- A GUI is built by putting components into
containers - The job of a Container is to hold and display
Components - Some frequently used types (subclasses) of
Component are JButton, JCheckbox, JLabel,
JTextField, and JTextArea - A Container is also a Component
- This allows Containers to be nested
- Important Container classes are JFrame, JApplet,
and JPanel - JFrame and JApplet both contain other containers
(container hierarchy) - You typically create and use JPanels directly
7To create an applet
- public class MyApplet extends JApplet
- The only way to make an applet is to extend
Applet or JApplet - You can add components to the applet
- The best place to add components is in init()
- You can paint directly on the applet, but
- its better to paint on a contained component
- Do all painting from paint(Graphics g)
8Swing Components
- Adding components to an applet is like adding
magnets to the fridge easy to move around.
Writing in the paint()method using drawString is
like finger painting your fridge permanently
placed. - Components (widgets) will appear behind strings
or graphics objects that are drawn on the screen
using paint. - In order to have access to the Swing components
youll need to use the command - import javax.swing.
9Example of relationship between paint()and init()
methods
- import javax.swing.
- import java.awt.
- public class PaintAndInitMethodsDemo extends
JApplet -
- Font f1
- Color c1, c2
- JButton b1
- public void init()
-
- setLayout(new FlowLayout())
- f1 new Font("Serif",Font.BOLD, 40)
- c1 Color.RED
- c2 Color.BLUE
- b1 new JButton("COSC 10403")
- add(b1)
- b1.setForeground(c2)
-
Paint method draws on top of components managed
by the layout manager for Japplet opposite for
Applets
10Component Class
- Widgets are derived from the Component class
(which is itself defined in the java.awt package) - The most important class in the java.awt package.
- It is also the largest, having 129 methods (at
present). - It is the parent(super) class for all the Java
widget classes and serves as the repository of
all the methods that are common to the widgets
(it is an abstract class and does not need to be
instantiated). - Hierarchy
11A JApplet is a Panel is a Container
java.lang.Object java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
so you can display things in an Applet
12Introduction to GUI Components
- Consider this simple program for creating Jlabels
for displaying text on an applet
import javax.swing. import java.awt. public
class LabelDemo extends JApplet JLabel l1
new Jlabel() JLabel l2, l3 public void
init() setLayout(new FlowLayout())
//default layout is BorderLayout.CENTER l2
new JLabel("Texas Christian University") l3
new JLabel("Fall, 2009")
add(l1) l1.setText(CoSc 10403)
add(l2) add(l3)
Note that components appear on the applet,
centered, top-down, left-to-right in the order
that they were added to the applet this is
FlowLayout. The default layout is
BorderLayout.CENTER
13The JLabel Class
- Labels allow the user to create GUI components
that can display un-selectable text or images. - Constructors (6 ways to build a JLabel)
- JLabel() - Creates a JLabel instance with no
image and with an empty string for the title. - JLabel(String text) - Creates a JLabel instance
with the specified text. - JLabel(String text, int horizontalAlignment)
- Creates a JLabel instance with the specified
text and horizontal alignment. - JLabel(Icon image) - Creates a JLabel instance
with the specified image. - JLabel(Icon image, int horizontalAlignment)
- Creates a JLabel instance with the specified
image and horizontal alignment. -
- JLabel(String text, Icon icon, int horizontalAlign
ment) - Creates a JLabel instance with the
specified text, image, and horizontal alignment. -
14JLabels
import java.awt. import javax.swing. public
class LabelDemo extends JApplet JLabel l1
new JLabel("COSC 10403") JLabel l2 new
JLabel("Texas Christian University",
JLabel.RIGHT) JLabel l3 public void
init() setLayout(new FlowLayout()) add(l1
) add(l2) l3 new JLabel("Fall, 2009",
JLabel.LEFT) add(l3)
15JLabels (continued)
- By specifying HTML code in a JLabel's text, you
can give the label various characteristics such
as multiple lines, multiple fonts or multiple
colors. - If the label uses just a single color or font,
you can avoid the overhead of HTML processing by
using the setForeground or setFont method
instead.
import javax.swing. import java.awt. public
class LabelStyles extends JApplet JLabel
l1 JLabel l2 JLabel l3 Font f1 public
void init() setLayout(new FlowLayout())
//default is BorderLayout.CENTER l1 new
JLabel("CoSc 10403 - Introduction to Computer
Science") l1.setForeground(Color.RED) l2
new JLabel("Texas Christian University") f1
new Font("Serif",Font.BOLDFont.ITALIC,15) l2.s
etFont(f1) l3 new JLabel("lthtmlgtltfont
colorBLUEgt Fall,lt/fontgt " "ltbgt semester lt/bgt"
"ltigt2009lt/igt") add(l1) add(l2) add(l3)
16import javax.swing. import java.awt. public
class JLabelImageDemo extends JApplet Image
img1, img2, img3, img4, img5 ImageIcon ic1,
ic2, ic3, ic4, ic5 JLabel l1, l2, l3, l4,
l5 public void init ( )
setLayout( new FlowLayout( ) ) img1
getImage( getCodeBase( ), "Pics/Elf.gif" )
img2 getImage( getCodeBase( ),
"Pics/ElfBox.gif" ) img3 getImage(
getCodeBase( ), "Pics/Santa.gif" ) img4
getImage( getCodeBase( ), "Pics/Computer.gif" )
img5 getImage( getCodeBase(),
"Pics/Seesaw.gif") // can't just add images
like this add( image ) ic1 new
ImageIcon( img1 ) ic2 new ImageIcon(
img2 ) ic3 new ImageIcon( img3 )
ic4 new ImageIcon( img4 ) ic5 new
ImageIcon( img5 ) // can't just add
ImageIcons like this add( imageIcon ) l1
new JLabel( ic1 )// have to add to a JLabel
// now can add the Jlabel to the applet l2
new JLabel("Elf with Box",ic2,JLabel.CENTER)
l2.setHorizontalTextPosition(JLabel.LEFT)
l3 new JLabel("Santa",ic3,JLabel.RIGHT)
l4 new JLabel("Computer",ic4,JLabel.CENTER
) l4.setHorizontalTextPosition(JLabel.CENTER)
l4.setVerticalTextPosition(JLabel.BOTTOM)
l5 new JLabel("Seesaw",ic5,JLabel.LEFT)
l5.setHorizontalTextPosition(JLabel.CENTER)
add(l1) add(l2) add(l3)
add(l4) add(l5)
Text position can be managed with setHorizontalT
extPosition(pos) setVerticalTextPosition(pos) Whe
re pos can be one of Horizontal
Vertical JLabel.LEFT JLabel.TOP JLabel.CENTER JLab
el.CENTER JLabel.RIGHT JLabel.BOTTOM
17The JButton Class
- A single button set up to initiate some action
when pushed by the user. - Note A Swing button can display both text and an
image. - Four Constructors that we will use
- Jbutton() - creates a button with no set text
or icon - Jbutton(String text) - creates a button with
text - Jbutton(Icon icon) - creates a button with an
icon - Jbutton(String text, Icon icon)- creates a button
with initial text and an icon.
18JButtons
- Swing permits
- Text
- JButton mybutton
- mybutton new JButton( Hello World )
- Image
- JButton mybutton
- mybutton new JButton( ImageIconVariable )
- Text and image
- JButton mybutton
- mybutton new JButton(three, ImageIconVariable
) -
- Text overlayed on top of image
- JButton mybutton
- mybutton new JButton( text w/ image,
ImageIconVariable ) mybutton.setHorizontalTextPo
sition(JButton.CENTER)
19JButton Demo
- import java.awt.
- import javax.swing.
- public class JButtonDemo extends JApplet
-
- JButton b1, b2, b3, b4, b5, b6
- Image img1, img2
- ImageIcon icon
- public void init()
-
- setLayout(new FlowLayout())
- b1 new JButton("Press")
- img1 getImage(getCodeBase(),"Pics/Earth.jpg")
- icon new ImageIcon( img1 )
- b2 new JButton( icon )
-
- img2 getImage( getCodeBase(),
"Pics/Mars.jpg)
20JButton Example font, color, center
- import javax.swing.
- import java.awt.
- public class JButtonImg2 extends JApplet
-
- JButton one, two,three
- Image img
- ImageIcon icon
- public void init( )
-
- setLayout( new FlowLayout( ) )
- one new JButton( "one" )
- one.setForeground( Color.red ) // change
color to red - img getImage( getCodeBase( ),
"buttonPoland.png" ) - icon new ImageIcon( img )
- two new JButton( icon )
21Textual Widgets
- Swing provides six text components that deal with
the display of text (only three are discussed in
our text) - JTextField, JPasswordField, and JTextArea.
- A JTextField looks like a box into which the user
can enter a single line of text. It might be used
to collect personal information about a user.(it
can be changed by the user by clicking and
dragging or by the program using the proper
methods). - A JTextArea provides space for more than a single
line of input or output. It might be used to
allow a user to add personal comments. - A JPasswordField provides specialized text fields
for password entry (for security reasons, a
password field does not show the characters that
the user types)
22The JTextField Class
- A GUI component that displays a single line of
text. Under program control it is possible to
specify whether or not the user is allowed to
edit the contents of the field. Because they may
be edited, a JTextField can be used to obtain
input from the user. - Four Constructors that we will use for building
JTextFields - JTextField() constructs a new JTextField.
- JTextField(int columns) constructs a new empty
JTextField with the specified number of columns. - JTextField(String text) constructs a new
JTextField initialized with the specified text. - JTextField(String text, int columns) constructs
a new JTextField initialized with the specified
text and columns.
23JTextField Demo Program
- import java.awt.
- import javax.swing.
- public class JTextFieldDemo1 extends JApplet
-
- JTextField tf1, tf2, tf3, tf4, tf5
- JPasswordField jpwf1
- Font f1 new Font("Serif",Font.ITALIC,15)
- JLabel l1
- public void init()
-
- setLayout(new FlowLayout())
- tf1 new JTextField() //default size
- tf2 new JTextField(10)
- tf2.setHorizontalAlignment(JTextField.RIGHT)
24The JTextArea Class
- A JTextArea is similar to a JTextField except
that it lets you view and edit multiple lines of
text. Its size can be specified when the object
is instantiated. - Text can be appended, inserted, or replaced at
any location (using click and drag). - Scrollbars may be attached (using a JScrollPane)
along the bottom and right side of the text area,
no matter how much text is actually contained in
it. The scrollbars can be used to bring desired
portions of the text into the visible area. - A JTextArea is defined by the JTextArea class, a
subclass of the JTextComponent class, which
contains several methods of its own. - JTextArea has a bound property for line wrapping
that controls whether or not it will wrap lines.
By default, the line wrapping property is set to
false (not wrapped).
25JTextArea Constructors
- There are four constructors that we will use in
the class - JTextArea() -
- Constructs a new JTextArea
- JTextArea(int rows, int columns)
- Constructs a new empty JTextArea with the
specified number of rows and columns. - JTextArea(String text)
- Constructs a new JTextArea with the specified
text displayed. - JTextArea(String text, int rows, int columns)
- Constructs a new JTextArea with the specified
text and number of rows and columns.
26JTextArea Demo
- import javax.swing.
- import java.awt.
- public class JTextAreaDemo extends JApplet
-
- JTextArea ta1, ta2, ta3, ta4, ta5, ta6, ta7
- JScrollPane jsp
- public void init()
-
- ta1 new JTextArea ( )
- //creates a JTextArea with 0 columns, 0 rows
- ta2 new JTextArea ( 3, 10 )
- //line wrapping is not enabled
- ta3 new JTextArea ( 3, 10 )
- ta3.setLineWrap(true)
- //line wrapping is enabled within the column
width specified - ta4 new JTextArea ( 3, 10 )
- ta4.setLineWrap(true)
27Active Widgets
- The Swing package supports a variety of window
components that the user can interact with to
initiate an action. - Javax.swing supports four distinct types of
components, each serving a different purpose
and each is used in specific situations - JCheckBox Class
- A component that can be selected or deselected
and which displays its state to the user. Often
a group of checkbox buttons are used to define a
set of options. Multiple options can be chosen
at the same time. - 2. JRadioButton Class
- A single component that displays a list of
choices when pushed. The current choice is shown
next to the button at all times but only a single
button can be chosen at one time. - 3. JComboBox Class
- A single component that displays a list of
choices when pushed. The current choice is shown
next to the button at all times. - 4. Jlist Class
- A component that allows the user to select one
or more objects from a list.
28The JCheckBox Class
- Seven Constructors that we will use
- JCheckBox()
- Creates an initially unselected check box button
with no text and no icon. - JCheckBox(String s)
- Creates a Checkbox with the given label and
unchecked (false) state. - JCheckBox(String s, boolean b)
- Creates a check box with text and specifies
whether or not it is initially selected. - JCheckBox(Icon icon)
- Creates an initially unselected check box with
an icon. - JCheckBox(Icon icon, boolean selected)
- Creates a check box with an icon and specifies
whether or not it is initially selected. - JCheckBox(String s, Icon icon)
- Creates an initially unselected check box with
the specified text and icon.
29JCheckBox Demo
- import java.awt.
- import javax.swing.
- public class JCheckBoxDemo extends JApplet
-
- JCheckBox cb1, cb2, cb3, cb4, cb5
- Image img1
- ImageIcon imgIcon1
- //Images for the selected state and unselected
state - Image notSelRedImg, selPaleRedImg
- //ImageIcons for the selected state and
unselected state - ImageIcon notSelRedImgIcon, selPaleRedImgIcon
- public void init()
-
- setLayout(new FlowLayout())
30JRadioButton Class
- An implementation of a radio button -- an item
that can be selected or deselected, and which
displays its state to the user. - Seven Constructors that we will use
- JRadioButton()
- Creates an initially unselected radio button
with no set text. - JRadioButton(String, text)
- Creates an unselected radio button with the
specified text. - JRadioButton(String text, boolean selected)
- Creates a radio button with the specified text
and selection state. - JRadioButton( Icon icon)
- Creates an initially unselected radio button
with the specified image but no text. - JRadioButton(Icon icon, boolean selected)
- Creates a radio button with the specified image
and selection state, but no text.
31JRadioButton Demo
- import java.awt.
- import javax.swing.
- public class JRadioButtonDemo extends JApplet
-
- JRadioButton blankRadioButton, onCampus,
offCampus, male, female - ButtonGroup housingGroup, genderGroup
- public void init( )
-
- blankRadioButton new JRadioButton()
- onCampus new JRadioButton( "Lives on Campus"
) - offCampus new JRadioButton( "Lives off
Campus" ) - male new JRadioButton( "Male" , true)
- female new JRadioButton( "Female" )
- housingGroup new ButtonGroup( )
- genderGroup new ButtonGroup()
32JRadioButton Demo
- import java.awt.
- import javax.swing.
- public class JRadioButtonDemo1 extends JApplet
-
- JRadioButton male, female
- ButtonGroup genderGroup
- //Images for the selected state and unselected
state - Image notSelMaleImg, selMaleImg,
notSelFemaleImg, selFemaleImg - //ImageIcons for the selected state and
unselected state - ImageIcon notSelMaleImgIcon, selMaleImgIcon,
notSelFemaleImgIcon, selFemaleImgIcon - public void init( )
-
- notSelMaleImg getImage(getCodeBase(),
"Pics/Male.png") - selMaleImg getImage(getCodeBase(),
"Pics/SelectedMale.png") - notSelFemaleImg getImage(getCodeBase(),
"Pics/Female.png") - selFemaleImg getImage(getCodeBase(),
"Pics/SelectedFemale.png")
Automatically selected.
33JComboBox Class
- A component that combines a button or editable
field and a drop-down list. Scrollbars are
automatically added to the drop-down list if
about seven or more items are in the list (this
number may be modified by using the
setPreferredSize method). - One Constructor that we will use
- JComboBox()
- Creates a JComboBox with a default data model.
34JComboBox Demo
- import javax.swing.
- import java.awt.
- public class JComboBoxDemo extends JApplet
-
- JComboBox majors
- public void init( )
-
- majors new JComboBox( )
- majors.addItem( "Select One Of" )
- majors.addItem( "Computer Science" )
- majors.addItem( "Mathematics" )
- majors.addItem( "Physics" )
- majors.addItem( "Engineering" )
- majors.addItem( "Geology" )
- setLayout( new FlowLayout( ) )
- add( majors )
35The List Class (from AWT)
- A component that allows the user to select one or
more objects from a list - somewhat like a
permanently expanded JComboBox. The JList class
is intuitively more difficult to understand than
the analogous List class in AWT. Consequently,
we will use the AWT List component in this
course. - Appears as a component with a collection of
items, one per line. - Example
- Note
- When the mouse is clicked on one of the lines, it
becomes highlighted and serves as the current
selection. - (2) A List object may behave in one of two ways.
- clicking on an item may turn off any currently
highlighted rows (the single selection mode). -
- clicking on an item may highlight it without
influencing any of the other already highlighted
rows (the multiple-selection mode). A shift-click
operation.
36The List Class
import java.awt. import java.applet. public
class ListDemoProgram extends Applet List l1
new List() List l2 new List(6) List l3
new List(5, true) public void init()
add(l1) add(l2) add(l3) l3.add("RO
TC") l3.add("Honor's Program") l3.add("Ban
d") l3.add("Student Government") l3.add("A
thletics")
- Three Constructors
- List()
- Creates a default-sized List object in
single-selection mode. - List(int rows)
- Creates a List object in single-selection mode
with the specified number of rows. - List(int r, boolean b)
- Creates a List object with the specified number
of rows, and if the argument is false, the
created List is in single-selection mode. - Must use methods
- void add(String item)
- Adds a new item (to the bottom of the list) with
the given label to this List object. - void add(String s, int i)
- Adds a new item (in the position indicated by
index) with the given label to this List object.
Items are shifted down to make room for the new
entry.
37Some Useful Methods in the JLabel Class
- void setText (String text) Sets the text of the
specified Label to that given in the argument. - Example
- blanklabel.setText(Now something)
- String getText() Returns a String object whose
value is the same as that of this JLabels
text. - Example
- String str blanklabel.getText()
- Alignment methods
- int getHorizontalAlignment()int
getVerticalAlignment() - void setHorizontalAlighment(int alignment)
- void setVerticalAlignment(int alignment)
- Icon getIcon (String text) Returns the graphic
image that the label displays. - void setIcon (Icon icon) Defines the icon this
component will display.
38Useful Methods in the JButton class
- void setText (String s)Sets the JButtons label
to be the specified string. - Example
- cancelB.setText(Cancel)
- String getText()Gets the label of the specified
Jbutton. - Example
- String s b1.getText()
- void setActionCommand (String s)Sets command
name for action event fired by this Jbutton. - Example
- JButton b1 new JButton(Cancel)
- b1.setActionCommand(B1)
- String getActionCommand()Returns the command
name of the action event fired by this
JButton. - Example
- String str
- str b1.getActionCommand()
39Commonly used TextField TextArea Methods
- TextFields
- void setColumns(int columns)
- sets the width of this JTextField to be enough
to hold columns characters (must be gt zero) - int getColumns()
- returns the current width, in columns, of this
JTextField. - String getSelectedText()
- returns the selected text in this JTextField.
- String getText()
- returns the contents of the JTextField.
- void setText(String string)
- set the contents of the JTextField to the
specified argument. - TextAreas
- int getColumns()
- returns the current width, in columns, of this
JTextArea. - int getRows()
- returns the current height, in rowes, of this
JTextArea. - void append(String str)
40Commonly used TextComponent Methods
- TextComponent
- String getSelectedText()
- returns the text that has been selected in this
text component. - String getText()
- returns the text that is in this text component.
- void setText(String s)
- Sets the text in this text component to the
string provided. - void setEditable(boolean b)
- Sets the flag that determines whether this text
component can be changed.
41Some JComboBox Methods
- void add(String item) already seen!!!
- Adds a new item with the given label to the list
of this JComboBox object. - int getItemCount()
- Returns the number of items currently in this
JComboBox object. - String getItemAt(int index)
- Returns the text of the item that is currently in
the index position. - int getSelectedIndex()
- Returns the index of the currently selected item.
- String getSelectedItem()
- Returns the text of the currently selected item.
- void insertAt(String item, int index) already
seen!!! - Inserts a new item string in the list in the
given index position. - void remove(int index)
42Some Useful JCheckBox JRadioButton Methods
- JCheckBox
- void setText(String label)
- Sets the label of this JCheckBox.
- String getText(String label)
- Returns a string containing the label text of
this JCheckBox. - boolean getState()
- Returns the current state (true or false) of
this JCheckBox. - void setSelected(boolean state)
- Sets the current state of this JCheckBox.
- void setSelectedIcon(Image image)
- Sets the selected icon for the JCheckBox
- JRadioButton
- Icon getSelectedIcon()
43Some Useful List Methods
- void delItems(int start, int end) //Removes a
inclusive range of items from the List. - void deselect(int index) //Turns off the
selection of the item in position index. - String getItem(int index) //Returns the text of
the item in position index in the List. - int getItemCount() //Returns the number of
items in the List. - int getRows() //Returns the number of rows in
this List item. - int getSelectedIndex() //Returns the index of
the current selection (-1 if none). - boolean isMultipleMode()
- Returns true if this List is in
multiple-selection mode (else false). - void remove(int index)
- Remove the item at the given index from the List.
- void remove(String item)
- Removes the item with the given string from the
List. - void removeAll()
- Removes all items from the List.
- void replaceItem(String newItem, int index)
- Replaces the item in position index with the text
given by the argument. - void select(int index)
- Selects the item in position index.
- void setMultipleMode(boolean m)
44Some Other Useful Methods
- void setVisible(boolean b) // makes the current
component visible or not. - void setEnabled(boolean b) // makes the current
component visible or not. - void setEditable(boolean b) // makes the current
component editable or not. - void setForeground(Color c) // sets the
Foreground color of the object to the specified
value. - void setBackground(Color c) // sets the
Background color of the object to the specified
value. - void requestFocus() // requests that this
component gets the input focus - void validate() // ensures that the
component has a valid layout.
45How do the paint()and init() methods relate?
- import java.awt.
- import javax.swing.
- public class PaintMethodDemo extends JApplet
-
- int i 0
-
- List l new List(5)
- JComboBox c new JComboBox()
-
- public void init()
-
- setLayout(new FlowLayout())
- add(c)
- add(l)
-
- public void paint(Graphics g)
-
- i i 1
Note new values are added to each Component
every time the applet window size changes.