1 Windows, Networking and other Tidbits Chapter Fourteen.
-
Upload
lynette-alaina-west -
Category
Documents
-
view
216 -
download
0
Transcript of 1 Windows, Networking and other Tidbits Chapter Fourteen.
1
Windows, Networking and Windows, Networking and other Tidbitsother Tidbits
Chapter Fourteen
2
Topics:Topics:
Windows, menus and dialog boxes– allow real pop up windows now from
Java applets Networking - load HTML from
browser, retrieve files from web sites work with generic sockets
Extra stuff
3
Windows, menus and Windows, menus and dialog boxesdialog boxes Frames AWT Window class
provides for windows that are independent (own titles, resize handels, menu bars)
Subclasses: Frame - fully functioning window
with menubar Dialog - more limited
4
To create a frameTo create a frame
new Frame( ) // = no title new Frame(String) has given title Frames are containers “like panels” default layout is BorderLayout
– win = new Frame(“My Way Cool Window”);– win.setLayout(new Borderlayout(10,20));– win.add(“North”, new Button(“Start”));– win.add(“Center”, new Button(“Move”));
5
Sizes moves location Sizes moves location show hideshow hide resize( ) to set size move( ) to set location location( ) can tell the applet
window is on screen win.resize(100, 200); Dimension d = location( ); win.move(d.width + 50, d.height +
50);
6
When you create a window it is invisable
show( ); // to make it appear hide( ); // to make it disappear
7
A popup window 14-1A popup window 14-1 public class GUI extends
java.applet.Applet { Frame window; public void init( ) {
– add(new Button(“Open Window”));– add(new Button(“Close Window”));– window = new MyFrame(“A Popup
Window”);– window.resize(150, 150);
window.show( );
8
public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) {
String label = (String)arg; if (label.equals(“Open Window”)) { if (!window.isShowing( ) )
– window.show( ); } else if (label = = “Close Window”) { if (window.isShowing( ) )
– window.hide( ); } return true; }
9
List 14.1 contd.List 14.1 contd.
else return false; } } class MyFrame extends Frame { Label l // lowercase L is variable MyFarame(String title) { Super(title); setLayout(new GridLayout(1 ,1)); //ones l = new Label(“This is a Window”,
Label.center); add(l); } // l is lower L
10
Programming hint: Do Not Programming hint: Do Not use lowercase letter L’s use lowercase letter L’s they look too much like they look too much like the digit One....the digit One....I keep telling publishers I keep telling publishers that and have done it that and have done it myself - choose something myself - choose something else. Old time keypunch else. Old time keypunch operators got sheets in operators got sheets in the writers hand Z vs. 2, l the writers hand Z vs. 2, l vs. 1 vs. 1This is not a new This is not a new concept...concept...
11
Menus and MenubarsMenus and Menubars
To create:– MenuBar mb = new MenuBar( );
Set as default:– window.setMenuBar(mb);
Add individual menus (File, Edit etc.) menu m = new menu(“file”); mb.add(m); // Some systems NOT All // would allow mb.setHelpMenu(m);
12
Menu ItemsMenu Items
Instances of the class MenuItem– Menu m = new Menu(“Tools”);
m.add(new MenuItem(“Info”)); Instances of the class
CheckBoxMenuItem Other menus with their own items Seperators = lines that divide
groups
13
SubmenusSubmenus
To create: Menu sb = new Menu (“sizes”); m.add(sb) // sub to m in previous
slide sb.add(new MenuItem(“Small”)); medium and large etc. can also be
added
14
CheckboxMenuItemCheckboxMenuItem
A menu item with a checkbox CheckboxMenuItem coords = new
CheckBoxMenuItem(“Show Coordinates”);
m.add(coords); Again m from previous menu
Any menu can be enable( ) disable( )
15
Menu ActionsMenu Actions
public boolean action(Event evt, Object arg) { if (evt.target instanceof MenuItem) {
String label = (String)arg; if(label.equals(“Show Coordinates”))
toggleCoords( ); else if (label.equals(“Fill”))
fillcurrentArea( ); return true; } else return false; }
16
Add a menu: Window from class MyFrame
MyFrame(String title) {– Super(title);– MenuBar mb = new MenuBar( );– Menu m = new Menu(“Colors”);– m.add(new MenuItem(“Red”));– m.add(new MenuItem(“Blue”));– m.add(new MenuItem(“Green”));– m.add(new MenuItem(“-”));– m.add(new CheckboxMenuItem(“Reverse
Text”)); mb.add(m); mb.setHelpMenu(m);– setMenuBar(mb); // ... }
17
To run the last slide you need an action( ) method:
public boolean action(Event evt, Object arg) { String label = (String)arg;
if (evt.target instanceof MenuItem) { if (label.equals (“Red”))
setBackground(Color.red); else if (label.equals(“Blue”))
setBackgroundColor.blue); else if (label.equals(“Green”))
setBackgroundColor.green); return true; }
18
if (evt.target instanceof CheckboxMenuItem) {
if (getForeground( ) = = Color.balck)
setForeground(Color.white); else setForeground(Color.black); return true; } return false; }
19
Dialog BoxesDialog Boxes
transient windows - popup with warnings ask for info. etc.
Two types in AWT:– Dialog class = generic– FileDialog = platform specific
(save/open)files To create: Dialog(Frame, boolean) initial invisable
– true = modal false not modal
20
Dialog(Frame, String, boolean) same as last slide BUT has titlebar and title
can be show( ) hide( ) just like Frames To add: m.add(new MenuItem(“Set Text...”)); dl = new Dialog(this, “Enter Text”, true); dl.setLAyout(new GridLayout(2, 1, 30,
30)); tf = new TextField(l.getText( ), 20); dl.add(tf); dl.add(new Button(“OK”)); dl/resize(150, 75); // Choose OK =
dismiss
21
File Dialogs - Can’t File Dialogs - Can’t access or Severe access or Severe restrictions on local restrictions on local system Really just for system Really just for stand alonestand alone To create: FileDialog (Frame, String) FileDialog(Frame, String, int) //
(load/save)– FileDialog.SAVE. OR FileDialog.LOAD
FIleDialog fd = new FileDialog(this, “FileDialog”);
fd.show( );
22
Window EventsWindow Events
WINDOW-DESTROY WINDOW-EXPOSE // brought forward WINDOW-ICONIFY WINDOW-DEICONIFY WINDOW-MOVED
Can test for all of these in the Event class
23
AWT in Stand Alone AWT in Stand Alone ApplicationsApplications Can use all the applet stuff: Can use Graphics etc.
24
Networking in JavaNetworking in Java
ShowDocument( ) // Load - link to other web page
openStream( ) open connect to URL
Socket classes: Socket and ServerSocket open standard socket connections (read/write to them)
25
Create Links inside Create Links inside AppletsApplets URL class To create a new URL URL(String, String, int, String)
– http ftp gopher file– host name (www.lne.com,
ftp.netcom.com)– a port number (80 for http)
URL(String, String, String) Same as above minus port number
URL(String) String should include “All”
26
Srting url = Srting url = “http//www.yahoo.com)/”);“http//www.yahoo.com)/”); try ( theURL = new URL(url); { catch (MAlformedURLException e) {
– System.out.println(“Bad URL: “ + theURL);
– } After you have the URL Link it: getAppletContext( ).showDocument
(theURL):
27
Bookmark buttonsBookmark buttons
import java.awt.*; import java.net.URL; import
java.net.MalformedURLExceptions; public class ButtonLink extends
java.applet.Applet { Bookmark bmlist[] = new
Bookmark[3];
28
public void init( ) { bmlist[0] = new Bookmark(“Laura’s
Home Page”, “http://www.lne.com/lemay/”);
bmlist[1] = new Bookmark(“Yahoo”, “http://www.yahoo.com”);
bmlist[2] = new Bookmark(“Java Home Page”, “http://www.java.sun.com”);
setLayout(new Bookmark(“GridLayout(bmlist.length,1,10,10)); for(int i=0; i< bmlist.length; i++);
add(new Button(bmlist[i].name)); } }
29
public boolean action(Event evt, Object arg) {
if(evt.target instanceof Button) { linkto((String) arg); return true } else return false; } Void LinkTo(String name) { URL theURL = null; for (int i=0; i <
bmlist.length; i++) { if (name.equals(bmlist[i].name))
theURL = bmlist[i].url; }
30
if (theURL != null) getAppletContext( ).showDocument(theURL); } }
class Bookmark { String name; URL url; Bookmark(String name, String theURL) { this.name = name; try { this URL = new URL(theURL); } catch (MalformedURLException e) { System.out.println(“Bad URL: “ +
theURL); } } }
31
Opening Web ConnectionsOpening Web ConnectionsopenStream( )openStream( ) To open a net connection - given URL try { inputStream in =
theURL.openStream( ); DataInputStream data new
DataInputStream((new BufferedInputStream(in); String line;
while (( line = data.readLine( )) != null) {
System.out.println(line); } }
32
catch (IOException e) { System.out.Pintln(“IO Error: “ +
e.getMessage( )); }
33
The Get (Poe’s) Raven The Get (Poe’s) Raven classclass Page 293 - 294 complete text Note the following: All the imports - more than ever
before (7) public class GetRaven extends
java.applet.Applet implements Runnable { URL theURL; Thread runner; TextArea ta = new Text(“Getting text
...”,30,70);
34
public void init( ) { String url =
“http:/www.lne.com/Web/Java/raven.txt”;
try { this.theURL = new URL(url); } catch (MalformedURLException e) {
– System.out.println(“Bad URL: “ + theURL);
– } add(ta); } NOT going to review insets( )
– start( ) stop( )
35
public void run( ) { InputStream conn;
data = new DataInputStream(new BufferedInputStream(conn));
while((line = data.readLine( )) != null) {– buf.append(line + “\n”); }– ta.setText(buf.toString( )); }– catch (IOException e)
{ System.out.println(“IO Error:” + e.getMessage( )); } } }
36
URLconnection ClassURLconnection Class
openStream( ) simple for URLconnection
class.URLconnection– A way to retrieve files
37
SocketsSockets
Java provides socket and ServerSocket
They provide for networking applications beyond what URL and URLconnection classes offer
Socket connection = new Socket(hostname, portnum);
38
DataInputStream in = new DataINputStream( new BufferedINputStream(connection.getInputStream( )));
DataoutputStream out = new DataOutputStream( new BufferedOutputStream(connection.getOutputStream( )));
connection.close( ) // when done & hide it ServerSocket sconnection = new
ServerSocket(8888); sconnection.accept( );
See java.net for more info java sockets
39
Other Applet HintsOther Applet Hints
showStatus( ) // use print error etc. msgs:
getAppletContext( ).showStatus(“Change the color); // access browser features
Applet Information:– public String getAppletInfo( ) {– return “GetRaven copyright 1995 Laura
Lemay;’ }
40
Communication Between Communication Between AppletsApplets for (Enumeration e =
getAppletContext( ).getApplets( ); e.hasMoreElements( );) { Applet current = (Applet)
(e.nextElement( )); current.sendMessage }
– //getApplets( ) returns Enumeration Object– A list of Applets on the page
41
to call specific applet: <P> This applet sends information: <APPLET CODE=“MyApplet.class”
WIDTH=100 HEIGHT=150 NAME = “sender””> </APPLET> <P>This applet receives
information from the sender: <APPLET CODE=“MyApplet.class”
WIDTH=100 HEIGHT=150 NMAE=“receiver”><?APPLET>
42
Finally:Finally:
//get ahold of the receiver applet Applet receiver =
getAppletContext( ).getApplet(“receiver”);
//tell it to update itself.– RECEIVER.UPDATE(TEXT, VALUE);