Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Windows, Networking and other Tidbits Chapter Fourteen 1 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 2 Windows, menus and dialog 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 3 To 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”)); 4 Sizes moves location show 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); 5 When you create a window it is invisable show( ); // to make it appear hide( ); // to make it disappear 6 A 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( ); 7 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; } 8 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 9 Programming hint: Do Not use lowercase letter L’s they look too much like the digit One.... I keep telling publishers that and have done it myself - choose something else. Old time keypunch operators got sheets in the writers hand Z vs. 2, l vs. 1 This is not a new concept... 10 Menus 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); 11 Menu 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 12 Submenus 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 13 CheckboxMenuItem 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( ) 14 Menu 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; } 15 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); 16 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; } 17 if (evt.target instanceof CheckboxMenuItem) { if (getForeground( ) = = Color.balck) setForeground(Color.white); else setForeground(Color.black); return true; } return false; } 18 Dialog 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 19 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”)); 20 File Dialogs - Can’t access or Severe restrictions on local system Really just for stand alone To create: FileDialog (Frame, String) FileDialog(Frame, String, int) // (load/save) – FileDialog.SAVE. FileDialog.LOAD OR FIleDialog fd = new FileDialog(this, “FileDialog”); fd.show( ); 21 Window Events WINDOW-DESTROY WINDOW-EXPOSE // brought forward WINDOW-ICONIFY WINDOW-DEICONIFY WINDOW-MOVED Can test for all of these in the Event class 22 AWT in Stand Alone Applications Can use all the applet stuff: Can use Graphics etc. 23 Networking 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) 24 Create Links inside Applets 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” 25 Srting url = “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): 26 Bookmark buttons import java.awt.*; import java.net.URL; import java.net.MalformedURLExceptions; public class ButtonLink extends java.applet.Applet { Bookmark bmlist[] = new Bookmark[3]; 27 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++); 28 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; } 29 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); } } } 30 Opening Web Connections 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); } } 31 catch (IOException e) { System.out.Pintln(“IO Error: “ + e.getMessage( )); } 32 The Get (Poe’s) Raven class 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); 33 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( ) 34 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( )); } } } 35 URLconnection Class openStream( ) simple for URLconnection class.URLconnection – A way to retrieve files 36 Sockets Java provides socket and ServerSocket They provide for networking applications beyond what URL and URLconnection classes offer Socket connection = new Socket(hostname, portnum); 37 DataInputStream in = new DataINputStream( new BufferedINputStream(connection.getIn putStream( ))); DataoutputStream out = new DataOutputStream( new BufferedOutputStream(connection.getO utputStream( ))); connection.close( ) // when done & hide it ServerSocket sconnection = new ServerSocket(8888); sconnection.accept( ); 38 Other 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;’ } 39 Communication Between Applets 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 40 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> 41 Finally: //get ahold of the receiver applet Applet receiver = getAppletContext( ).getApplet(“receiver”); //tell it to update itself. – RECEIVER.UPDATE(TEXT, VALUE); 42