TCU CoSc 10403 Programming with Java
Download
Report
Transcript TCU CoSc 10403 Programming with Java
TCU CoSc 10403
Introduction to Programming
(with Java)
Java Components
Components
•
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)
AWT:
SWING:
Visual Guide to Java Swing Components
Borrowed from:
http://java.sun.com/docs/books/tutorial/ui/features/components.html
Swing 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 can’t mix them
– Actually, you can, but it’s tricky and not worth doing
• Basic controls are practically the same in both
– AWT:
– Swing:
Button b = new Button ("OK");
JButton b = new JButton("OK");
• Swing gives far more options for everything (buttons with
pictures on them, etc.)
To 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.)
– It’s usually best to declare Components as instance variables, and
– Define them in your applet’s 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
Containers 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)
6– You typically create and use JPanels directly
To 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…
…it’s better to paint on a contained component
• Do all painting from paint(Graphics g)
Swing 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 –
you’ll need to use the command:
import javax.swing.*;
Example 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);
}
public void paint( Graphics g )
{
g.setColor(c1);
g.setFont(f1);
g.drawString("Hello World - Let's
see!",30,30);
}
}
Paint method draws on top of
components managed by the layout
manager for Japplet – opposite
for Applets
Component 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:
Applet
A 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
Introduction 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);
Note that components appear on the applet,
add(l3);
}
}
centered, top-down, left-to-right in the
order that they were added to the applet –
this is FlowLayout.
The default layout for a JApplet is
BorderLayout.CENTER
The 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 horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal
alignment.
JLabels
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);
}
}
JLabels (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.BOLD+Font.ITALIC,15);
l2.setFont(f1);
l3 = new JLabel("<html><font color=BLUE> Fall,</font> " + "<b> semester </b>" + "<i>2009</i>");
add(l1);
add(l2);
add(l3);
}
}
import 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);
Text position can be managed with:
l3 = new JLabel("Santa:",ic3,JLabel.RIGHT);
l4 = new JLabel("Computer:",ic4,JLabel.CENTER);
l4.setHorizontalTextPosition(JLabel.CENTER);
l4.setVerticalTextPosition(JLabel.BOTTOM);
setHorizontalTextPosition(pos)
setVerticalTextPosition(pos)
l5 = new JLabel("Seesaw",ic5,JLabel.LEFT);
l5.setHorizontalTextPosition(JLabel.CENTER);
Where pos can be one of:
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
}
}
Horizontal
JLabel.LEFT
JLabel.CENTER
JLabel.RIGHT
Vertical
JLabel.TOP
JLabel.CENTER
JLabel.BOTTOM
The 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.
JButtons
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.setHorizontalTextPosition(JButton.CENTER);
Poland
18
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”);
b3 = new JButton( "Mars", new ImageIcon( img2 ) );
b4 = new JButton("Earth",icon);
b4.setHorizontalTextPosition(JButton.CENTER);
b4.setVerticalTextPosition(JButton.BOTTOM);
b5 = new JButton("Earth",icon);
b5.setBorderPainted(false);
b6 = new JButton("Earth", icon);
b6.setEnabled(false);
add(
add(
add(
add(
add(
add(
}
}
b1 );
b2 );
b3 );
b4 );
b5 );
b6) ;
JButton Demo
JButton Example: font, color, center
import
import
javax.swing.*;
java.awt.*;
public class JButtonImg2 extends
{
JButton one, two,three;
Image img;
ImageIcon icon;
JApplet
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 );
img = getImage( getCodeBase( ), "buttonYellowstone.png"
three = new JButton( "Yellowstone", new ImageIcon( img
three.setFont( new Font( "Serif", Font.BOLD, 26 )); //
three.setHorizontalTextPosition( JButton.CENTER );
//
add( one );
add( two );
add( three );
);
));
change font
center
}
}
20
Textual 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)
The 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.
JTextField Demo Program
import java.awt.*;
import javax.swing.*;
public class JTextFieldDemo1 extends JApplet
{
JTextField tf1, tf2, tf3, tf4, tf5;
Right
JPasswordField jpwf1;
Font f1 = new Font("Serif",Font.ITALIC,15);
alignment, red,
Serif font
JLabel l1;
public void init()
{
setLayout(new FlowLayout());
tf1 = new JTextField(); //default size
tf2 = new JTextField(10);
tf2.setHorizontalAlignment(JTextField.RIGHT);
tf2.setFont(f1);
tf2.setForeground(Color.RED);
tf3 = new JTextField("CoSc 10403");
tf4 = new JTextField("Enter name",25);
l1 = new JLabel("Enter Password:");
jpwf1 = new JPasswordField(12);
add(tf1);
add(tf2);
add(tf3);
add(tf4);
add(l1);
add(jpwf1);
}
}
Note: the length parameter for the
JTextField limits only the
number of characters that are
visible at any point in time – not
the number of characters that can
be entered into the field
(characters will scroll).
JPasswordField:
characters are concealed.
The 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).
JTextArea 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.
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 – nothing visible
ta2 = new JTextArea ( 3, 10 );
//line wrapping is not enabled – really more than 10 chars wide,
//grows as characters are inserted.
ta3 = new JTextArea ( 3, 10 );
ta3.setLineWrap(true);
//line wrapping is enabled within the column width specified // width doesn’t change
ta4 = new JTextArea ( 3, 10 );
ta4.setLineWrap(true);
ta4.setWrapStyleWord(true);
//enable both line wrapping and word boundary wrapping – width
//doesn’t change
ta5 = new JTextArea("CoSc 10403");
ta6 = new JTextArea ( "TCU rocks", 4, 10 );
ta7 = new JTextArea( 5, 10);
ta7.setLineWrap(true);
ta7.setWrapStyleWord(true);
jsp = new JScrollPane(ta7);
setLayout(new FlowLayout());
add(ta1);
add(ta2);
add(ta3);
add(ta4);
add(ta5);
add(ta6);
add(jsp);
}
}
JTextArea Demo
Active 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
1. 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.
The 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.
• JCheckBox(String s, Icon icon, boolean selected)
Creates an initially unselected check box with the specified text and icon.
import java.awt.*;
import javax.swing.*;
public class JCheckBoxDemo extends JApplet
{
JCheckBox cb1, cb2, cb3, cb4, cb5;
Image img1;
ImageIcon imgIcon1;
JCheckBox Demo
No way to know
when this
selection is made.
//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());
cb1 = new JCheckBox( );
cb2 = new JCheckBox( "CoSc 10403" );
img1 = getImage(getCodeBase(), "Pics/Earth.jpg");
imgIcon1 = new ImageIcon(img1);
cb3 = new JCheckBox( imgIcon1 );
cb4 = new JCheckBox( "TCU", false);//true causes it to be selectedd
notSelRedImg = getImage(getCodeBase(), "Pics/Red.png");
notSelRedImgIcon = new ImageIcon(notSelRedImg);
selPaleRedImg = getImage(getCodeBase(), "Pics/PaleRed.png");
selPaleRedImgIcon = new ImageIcon(selPaleRedImg);
cb5 = new JCheckBox( "Red", notSelRedImgIcon );
cb5.setSelectedIcon(selPaleRedImgIcon);
add(cb1);
add(cb2);
add(cb3);
add(cb4);
add(cb5);
}
}
When selected – a second
image is displayed (due to
setSelectedIcon()).
JRadioButton 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.
•JRadioButton(String text, Icon icon)
Creates a radio button that has the specified text and image, and that is initially
unselected.
•JRadioButton(String text Icon icon, boolean selected)
Creates a radio button that has the specified text, image, and selection state.
import java.awt.*;
import javax.swing.*;
JRadioButton Demo
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();
housingGroup.add( onCampus );
housingGroup.add( offCampus );
genderGroup.add( male );
genderGroup.add( female );
setLayout( new FlowLayout( ) );
add( blankRadioButton);
add( onCampus ); add( offCampus );
add( male ); add(female);
}
}
JRadioButton 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");
notSelMaleImgIcon = new ImageIcon(notSelMaleImg);
selMaleImgIcon = new ImageIcon(selMaleImg);
notSelFemaleImgIcon = new ImageIcon( notSelFemaleImg);
selFemaleImgIcon = new ImageIcon(selFemaleImg);
male = new JRadioButton( "Male", notSelMaleImgIcon , true);
female = new JRadioButton( "Female", notSelFemaleImgIcon );
genderGroup = new ButtonGroup();
genderGroup.add( male ); genderGroup.add( female );
setLayout( new FlowLayout(
)
);
add( male ); male.setSelectedIcon(selMaleImgIcon);
add(female); female.setSelectedIcon(selFemaleImgIcon);
}
}
Automatically
selected.
JComboBox
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 setMaximumRowCount(int count) method).
One Constructor that we will use:
•JComboBox()
Creates a JComboBox with a default data model.
JComboBox 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 );
}
}
The 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.
•Appears as a component with a collection of items, one per line.
•Example:
•Note:
(1)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 multipleselection mode). A shift-click operation.
The List Class
Three Constructors:
• List()
Creates a default-sized List object in singleselection mode.
• List(int rows)
Creates a List object in single-selection mode
with the specified number of rows.
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);
• List(int r, boolean b)
public void init()
{
add(l1);
add(l2);
add(l3);
l3.add("ROTC");
l3.add("Honor's Program");
l3.add("Band");
l3.add("Student Government");
l3.add("Athletics");
}
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.
}
JList
• Used to display a list of items
– Text
– Images
– Buttons
37
JList
• First element is at index 0 (zero)
• Create a model to work on the list:
– DefaultListModel model;
model = new DefaultListModel( );
• Create the list with this model
– JList list;
list = new JList( model );
• To add items, use the addElement method on the model variable to add
items at the end of the list or the add method on the model variable and
specify the index in the list of where to add it.
– model.addElement( “grapes” );
– model.add( 0, “bananas” );
38
JList
• To specify how many rows should be visible (the rest are
scrollable) use:
– list.setVisibleRowCount( number );
• To remove items, use the remove method on the model
– model.remove( 1 );
// remove item at index 1
– model.remove( “bananas” );
• To get scrollbars, put in a JScrollPane
JScrollPane spane;
spane = new JScrollPane( list );
add( spane );
39
JList – Example - add
40
JList – Example - addElement
41
JList – Example - JScrollPane
import javax.swing.*;
import java.awt.*;
public class JListEx extends
{
DefaultListModel model;
JList majors;
JApplet
public void init( )
{
setLayout( new FlowLayout( ) );
model = new DefaultListModel( );
majors = = new JList( model );
model.addElement( "CS" );
model.addElement( "Math" );
model.addElement( "History" );
model.addElement( "Leisure Studies" );
model.addElement( "Psych" );
majors.setVisibleRowCount( 3 );
JScrollPane spane = new JScrollPane( majors );
add( spane );
}
}
42
JList – Example - Images
import javax.swing.*;
import java.awt.*;
public class JListExImage extends JApplet
{
DefaultListModel model;
JList countries;
public void init( )
{
model = new DefaultListModel( );
countries = = new JList( model );
Image img = getImage( getCodeBase( ), “Poland.png" );
ImageIcon ic = new ImageIcon( img );
model.add( 0, ic );
model.add( 1, “Europe" );
img = getImage( getCodeBase( ), “Laos.png" );
ic = new ImageIcon( img );
model.add( 2, ic );
model.addElement( “Asia" );
img = getImage( getCodeBase( ), “Cambodia.png" );
ic = new ImageIcon( img );
model.addElement( ic );
setLayout( new FlowLayout( ) );
countries.setVisibleRowCount( 3 );
JScrollPane spane = new JScrollPane( countries);
add( spane );
}
}
43
JList - constructors
• Constructors
– JList list;
list = new JList ( );
• Creates a new empty list
– DefaultListModel model;
JList list;
model = new DefaultListModel( );
list = new JList( model );
• Creates a list based on a default model, such that you can add items to
the model
– JList list;
list = new JList( array );
• Creates a list based on the array
• We haven’t done arrays yet…. stay tuned
44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JList Example
public class JListDemo extends JApplet
{
String[] classification = {"Fresh", "Soph", "Junior", "Senior"};
JList list0 = new JList(classification);
JScrollPane pane0 = new JScrollPane(list0);
// since build on the classification data model – which is a fixed
// size - no more items may be added.
public void init()
{
setLayout(new FlowLayout());
add(pane0);
list0.setVisibleRowCount(3);
}
}
import java.awt.*;
import javax.swing.*;
JList Example
public class JListDemo1 extends JApplet
{
DefaultListModel model = new DefaultListModel();
JList list1 = new JList(model);
JScrollPane pane1 = new JScrollPane(list1);
public void init()
{
setLayout(new FlowLayout());
add(pane1);
// add selections to the data model
model.addElement("JList");
model.addElement("Computer Science");
model.addElement("Math");
model.addElement("Engr");
model.addElement("Phys");
list1.setVisibleRowCount(3);
//.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //the default
//ist1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); //shift key???
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //command key??
}
}
JList - methods
• Useful Methods
– int getSelectedIndex( )
• Returns the index of the item that is selected
– Object getSelectedValue( )
• Returns the object that is selected
– void setSelectionMode( int mode )
• Where mode can be:
–
–
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION (default)
allows users to select more than one in the list
– … more in API in book and on the website
47
Some 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 JLabel’s 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.
Useful Methods in the JButton class
•
void setText (String s);
Sets the JButton’s label to be the specified string.
o
•
Example
•
cancelB.setText(“Cancel”);
String getText();
Gets the label of the specified Jbutton.
o
•
Example:
•
String s = b1.getText();
void setActionCommand (String s);
Sets command name for action event fired by this Jbutton.
o
•
Example:
•
JButton b1 = new JButton(“Cancel”);
•
b1.setActionCommand(“B1”);
String getActionCommand();
Returns the command name of the action event fired by this JButton.
o
Example:
•
•
String str;
str = b1.getActionCommand();
Commonly used TextField & TextArea Methods
•
TextFields
void setColumns(int columns)
sets the width of this JTextField to be enough to hold columns characters (must be >= 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)
changes the text of this object by appending the characters in the argument to the end of the current text (The JTextArea
version of string concatenation).
void setColumns(int columns)
changes the number of columns in this JTextArea. (No companion methods for rows).
void insert(String str, int position)
inserts the argument string into the current text, at the location given by the position argument. Example, “mud” becomes
“mustard” after insert(“star”,2). (Begin counting at 0).
void replaceRange(String str, int start, int end)
replaces the current text between start (included in the replacement) and end (not included in the replacement) with the
argument string. Example, “abcdefghi” becomes “ab*ghi” after replaceText(“*”,2,6). (Begin counting at zero,
string may be empty).
Commonly 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.
Some 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)
Removes the item at the given index position.
•
void removeAll()
Removes all items from this JComboBox object.
•
void selectIndex(int index)
Select the item in the given index position (numbered 0 to itemCount-1).
•
void selectItem(String item)
Selects the item in the list that matches the given string.
Some Useful JCheckBox & JRadioButton Methods
JCheckBox
•
void setText(String label)
•
String getText(String label)
•
boolean getState()
•
void setSelected(boolean state)
•
void setSelectedIcon(Image image)
Sets the label of this JCheckBox.
Returns a string containing the label text of this JCheckBox.
Returns the current state (true or false) of this JCheckBox.
Sets the current state of this JCheckBox.
Sets the selected icon for the JCheckBox
JRadioButton
•
Icon getSelectedIcon()
Returns the selected icon.
•
void setSelected(boolean b)
Sets the JRadioButton state to the specified argument.
Some 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()
–
•
void remove(int index)
–
•
Replaces the item in position index with the text given by the argument.
void select(int index)
–
•
Removes all items from the List.
void replaceItem(String newItem, int index)
–
•
Removes the item with the given string from the List.
void removeAll()
–
•
Remove the item at the given index from the List.
void remove(String item)
–
•
Returns true if this List is in multiple-selection mode (else false).
Selects the item in position index.
void setMultipleMode(boolean m)
–
Turns the multiple-selection mode on if the argument is true. Sets the mode to single-selection if the
argument is false.
Some 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()
•
void validate()
// requests that this component gets the input focus
// ensures that the component has a valid layout.
How 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();
Note: new values are
added to each Component
every time the applet
window size changes.
public void init()
{
setLayout(new FlowLayout());
add(c);
add(l);
}
public void paint(Graphics g)
{
i = i + 1;
//insert another TCU each time window is redrawn
c.addItem("TCU - " + i);
//insert another "CoSc 10403" each time window is redrawn
l.add("CoSc 10403 - " + i);
}
}