You are on page 1of 40

Java 2 for Beginners

Day 4
How would we write a
program to add 2 numbers?
n Let’s write it now.
Arrays and Vectors
n You create arrays using brackets:
int iarray[] = new int[12];
float temp[] = new float[100];

n Access elements using indexes in brackets


n Arrays have a length property

for( int i = 0; i < temp.length; i++) {


temp[i] = 0;
}
Two dimensional arrays
n Use two pairs of brackets
float x[][] = new float[12][10];

n Multi dimensional arrays unusual


n More common to have arrays of objects
n each of which holds several values
A Vector is an Unbounded Array
n Starts empty
n Vector vegies = new Vector();
n Add elements as any kind of objects
n vegies.addElement(“Radish”);
n vegies.addElement(“Rutabaga”);
n Get elements out
n String veg = (String)vegies.elementAt(2);
n Length of vector uses size() method
n int sz = veg.size();
Applications versus Applets
n An application is a stand-alone Java
program.
n Can access files, network, printer and can
exit.
n An applet runs inside a web page.
n Can only get files from its web server
n Cannot access any part of the client
computer (except by special permission)
An Applet has an init method
n instead of the Application’s constructor
public class tempcalc extends Applet implements ActionListener {
private CheckboxGroup grpTemper; //group radio buttons
private Label label1;
private TextField tempEntry; //edit box
private Checkbox fahr; //radio button
private Checkbox celsius; //radio button
private Label result; //result shown here
private Button compute; //compute when clicked
private Button quit; //exit when clicked
//-------------------------------------------------------
public void init() {
//initialize applet
setLayout(new GridLayout(6,1));
setBackground(Color.lightGray);

label1 = new Label("Enter temperature:");


add(label1);
An applet is loaded from a
web page
<HTML>
<BODY>
<APPLET CODE="tempcalc.class" width=200 height=300>
</APPLET>
</BODY>
</HTML>
Applets
n Must be on the same server as the web
page.
n Can be in another related subdirectory
n Require a Java JVM in the browser
n May introduce a pause when Java starts
n The applet starts in its init() method
n Provide possibility of elegant and
sophisticated user interfaces.
How Applets run
n The browser calls the init() method
n and then the start() method
n If window is obscured
n calls the stop() method
n When window is reshown
n calls the start() method
As a pedagogical stunt
n You can create a single program which runs
as an application and an applet.
public static void main(String arg[]) {
//create the frame
XFrame fr = new XFrame("Temperature calculation");
fr.setLayout(new BorderLayout());
//create the applet
Applet app = new tempcalc();
fr.add("Center",app); //add into the frame
fr.setSize(364, 225); //define its size

fr.show(); //show the frame


app.init(); //lay out the applet
app.start(); //start it
fr.pack(); //arrange applet inside frame
}

n Probably not terribly useful.


Creating Menus
n A menu is text in the bar across the
top.
n You add MenuItems to each Menu
object.
n AWT Menus only work on applications
n (Swing menus can work on applets)
Creating Menu Objects
public class MenuFrame extends XFrame implements ActionListener {
MenuBar mbar; //the menu bat
Menu File; //top level menus
Menu Setup;
MenuItem Open; //first menu
MenuItem Exit;
MenuItem Appearance; //second menu
Menu Preferences;
MenuItem Colors;
MenuItem Filetypes;
CheckboxMenuItem Sound;

public MenuFrame() {
super("Menu Demonstration");
setBackground(new Color(0x000f0fff));
mbar = new MenuBar(); //create menu bar
setMenuBar(mbar); //and add to Frame
File = new Menu("File",true); //Create two top level menu items
Setup = new Menu("Setup",false);
mbar.add(File); //and add to Menubar
mbar.add(Setup);
Adding MenuItems
n Add to each Menu object
/File menu is File->Open, separator, Exit
Open = new MenuItem("Open...");
Exit = new MenuItem("Exit");
Open.addActionListener (this);
Exit.addActionListener (this);
File.add(Open);
File.add(new MenuItem("-")); //separator
File.add(Exit);
MenuItems use ActionListeners
public void actionPerformed(ActionEvent evt) {
Object obj = evt.getSource ();
if (obj == Exit) {
System.exit(0);
}
if (obj == Open) {
FileDialog fdlg = new FileDialog(this,
"Open",FileDialog.LOAD);
fdlg.show();
}
}
Nested Menus
n Add MenuItems to MenuItems
Appearance = new MenuItem("Appearance");
Preferences = new Menu("Preferences");
Colors = new MenuItem("Colors");
Filetypes = new MenuItem("Filetypes");
Sound = new MenuItem("Sound");
Setup.add(Appearance);
Setup.add(Preferences); //add menu here for sub menus
Preferences.add(Colors);
Preferences.add(Filetypes);
Setup.add("Sound");
The Swing (JFC) Classes
n More sophisticated looking
n Better performance
n Not dependent on native window
controls
n Not supported natively in most
browsers, except Netscape 6
n Alternative Java plug-in slow to load
Using Swing
n “It’s spelled JFC, but pronounced
Swing.”
//always
import javax.swing.*;
//may also need
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
Swing components
n Have a variable look and feel
n Provide
n beveled border
n image buttons and menus
n tooltips when mouse hovers
n trees, tables
n more sophisticated lists
n most components just have a J-prefix
n JButton, JPanel, etc.
The Display Pane is one level
deeper
import javax.swing.*;

public class SimpleJFC extends JFrame {


public SimpleJFC() {
getContentPane().setLayout(new BorderLayout());
JButton b = new JButton(“Hi”):
getContentPane().add(b);
An Easier Way
import javax.swing.*;

public class SimpleJFC extends JFrame {


public SimpleJFC() {
Jpanel jp = getContentPane();
jp.setLayout(new BorderLayout());
Jbutton b = new Jbutton(“Hi”):
jp.add(b);
You can also set the look and feel
n Native (Windows or Motif)
n Swing (metal look)
n Mac look on Mac only
n We provide a JxFrame class which
n sets the native look and feel
n sets the Windows exit box
public class SimpleJFC extends JxFrame {
JButtons can have text and icons
private void setGUI() {
jp = new JPanel();
getContentPane().add(jp);
//create and add buttons
OK = new JButton("OK",new ImageIcon("color.gif"));
OK.setRolloverIcon(new ImageIcon("overColor.gif"));
OK.setToolTipText("Change background color");
Quit = new JButton("Quit", new ImageIcon("exit.gif"));
Quit.setToolTipText("Exit from program");
OK.addActionListener(this);
Quit.addActionListener(this);

jp.add(OK);
jp.add(Quit);
Checkboxes and Radio buttons
n JRadioButtons
n separate from checkboxes
n still must be made part of ButtonGroup
n Both can have images as well as text
n Both can have Tooltips
n The getState method returns true or
false for each of them.
JToggleButton
n Parent class to both JCheckbox and
Jradiobutton
n A text (or imaged) button that stays
“up” or “down”
JToolBar
n Container bar for tool buttons.
n Normally you put it in the North edge or
a BorderLayout
n any other edge will work as well
n Has 2 methods
JToolBar tb = new JToolBar();
tb.add(new Jbutton(“foo”)):
tb.addSeparator();
Demo of JToolBar,checks and
radios
n Note also elegant borders
How we create the toolbar
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

public class Buttons extends JxFrame


implements ActionListener {
private JToolBar toolbar;
private JCheckBox YMCA, Rotary,ACLU;
private JRadioButton Rep, Dem, Flat;
private JButton Clear, Quit;

public Buttons() {
super("Buttons and Checks");
JPanel jp = new JPanel();
getContentPane().add(jp);
jp.setLayout(new BorderLayout());
toolbar = new JToolBar();
jp.add("North", toolbar);
All of the buttons in the toolbar
Clear = new ToolButton(new ImageIcon("erase.gif"));
Quit = new ToolButton(new ImageIcon("stop.gif"));
toolbar.add(Clear);
Clear.setToolTipText("Clear all boxes");
Quit.setToolTipText("Exit from program");
toolbar.add(Quit);
Clear.addActionListener(this);
Quit.addActionListener(this);

toolbar.addSeparator();
JToggleButton a = new JToggleButton("a");
JToggleButton b = new JToggleButton("b");
JToggleButton c = new JToggleButton("c");
toolbar.add(a);
toolbar.add(b);
toolbar.add(c);

ButtonGroup tgroup = new ButtonGroup();


tgroup.add(a);
tgroup.add(b);
tgroup.add(c);
Checks and radios in center
JPanel center = new JPanel();
jp.add("Center", center);
center.setLayout(new GridLayout(1,2));
JPanel left = new JPanel();
JPanel right = new JPanel();
center.add(left);
center.add(right);
left.setLayout(new GridLayout(3,1));
right.setLayout(new GridLayout(3,1));

left.add(YMCA = new JCheckBox("YMCA"));


left.add(Rotary = new JCheckBox("Rotary"));
left.add(ACLU = new JCheckBox("ACLU"));

right.add(Rep = new JRadioButton("Republicrat"));


right.add(Dem = new JRadioButton("Demmican"));
right.add(Flat = new JRadioButton("Flat Earth"));
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(Rep);
bgroup.add(Dem);
bgroup.add(Flat);
Responding to Button clicks
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();

if (obj == Quit)
System.exit(0);

if (obj == Clear) {
YMCA.setSelected(false);
Rotary.setSelected(false);
ACLU.setSelected(false);
Rep.setSelected(false);
Dem.setSelected(false);
Flat.setSelected(false);
}
}
Swing Borders
n Make layouts look a lot more professional.
n All containers have a setBorder method.
n BevelBorder(n);
n CompoundBorder(inner, outer)
n EmptyBorder(t,l,b,r);
n used for spacing around JComponents
n EtchedBorder
n LineBorder(width, color)
n SoftBeveledBorder
n TitledBorder(title)
Using Titled Borders
n Just add to the panel
JPanel left = new JPanel();
JPanel right = new JPanel();
center.add(left);
center.add(right);
left.setLayout(new GridLayout(3,1));
right.setLayout(new GridLayout(3,1));
left.setBorder(new TitledBorder("Memberships"));
right.setBorder(new TitledBorder("Party"));
Using Beveled Borders
n Faux search app
Border edge = BorderFactory.createBevelBorder (BevelBorder.LOWERED );
sp.setBorder (edge);
sText.setBorder (edge);
The Swing JList
n Consists of
n a list
n a scroll pane
n a data model class
When you Create a JList
n You must put it inside a JScrollPane
n You must provide it with data
n easiest to use Vector or Array
private Vector makeData() {
Vector dlist = new Vector(); //create vector
dlist.addElement("Anchovies"); //and add data
dlist.addElement("Bananas");
dlist.addElement("Cilantro");
dlist.addElement("Doughnuts");
dlist.addElement("Escarole");
return dlist;
}
Putting the JList on the screen
//create scroll pane
JScrollPane sp = new JScrollPane();
jp.add("Center", sp); //add to layout
//create JList
list= new JList(makeData()); //create list with data
sp.getViewport().add(list); //add list to scrollpane
list.addListSelectionListener(this);
Listening to JList events
n Add a ListSelectionListener to the JList
n When an item is selected a
valueChanged event is generated
public void valueChanged(ListSelectionEvent e) {
text.setText((String)list.getSelectedValue());
}
JLists are actually much more
versatile
n Under the covers there is a data model class
n here we used a vector
n and a listener that can be changed when the
data changes
n the data model calls a fireContentsChanged
method which causes the JLIst to repaint with
new data.
n See Advanced Swing chapter for details.
Summary
n We’ve covered
n Vectors and arrays
n Applets vs Applications
n Menus
n Swing classes
n Borders
n JList events

You might also like