9. swing & networking

25
Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136) public class WindowUtilities { public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } } SWING The used SWING slides are all © 2001-2004 Marty Hall, Larry Brown: http://www.corewebprogramming.com 1.1 New Features SWING has brand new built-in controls like Image Buttons, Tabbed Panes, Sliders, Toolbars, Color Choosers, HTML text areas, lists, trees, and tables. A lot of small but valuable tools have been added (e.g. custom cursors, keyboard accelerators, tool-tips). It offers an increased customization of components. You might set things like borders, alignments and add images wherever you want. The pluggable look and feel is part of this increased customization (The new look & feel is the default value). In order to use the native look and feel, you need to set it explicitly: 1.2_Swing vs. AWT Programming All Swing components start with a capital J + a 2 nd capital letter, e.g. JFrame Lightweight components in Swing (formed by drawing in the underlying window) Swing uses the paintComponent, not paint() for drawing Never mix Swing and AWT component in a window !!! 1.3 Basic Components 1.3.1 JApplet: A JApplet contains the ContentPane [in java: getContentPane()] in which to add components. Changing Properties also applies to the ContentPane. The default LayoutManager is the BorderLayout (not FlowLayout)

Upload: pradeepkraj123

Post on 22-Nov-2014

111 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

public class WindowUtilities { public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting native LAF: " + e); } }

SWING The used SWING slides are all © 2001-2004 Marty Hall, Larry Brown: http://www.corewebprogramming.com

1.1 New Features

SWING has brand new built-in controls like Image Buttons, Tabbed Panes, Sliders, Toolbars, Color Choosers, HTML text areas, lists, trees, and tables. A lot of small but valuable tools have been added (e.g. custom cursors, keyboard accelerators, tool-tips). It offers an increased customization of components. You might set things like borders, alignments and add images wherever you want. The pluggable look and feel is part of this increased customization (The new look & feel is the default value). In order to use the native look and feel, you need to set it explicitly:

1.2_Swing vs. AWT Programming

• All Swing components start with a capital J + a 2nd capital letter, e.g. JFrame • Lightweight components in Swing (formed by drawing in the underlying

window) • Swing uses the paintComponent, not paint() for drawing • Never mix Swing and AWT component in a window !!!

1.3 Basic Components

1.3.1 JApplet: A JApplet contains the ContentPane [in java: getContentPane()] in which to add components. Changing Properties also applies to the ContentPane.

The default LayoutManager is the BorderLayout (not FlowLayout)

Page 2: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

Remember that you need to set the native look and feel explicitly, if you want to use it. The default look and feel is Metal (Java).

1.3.2 JFrame: The JFrame also uses the ContentPane and the Java look and feel (see JApplet).

The JFrame automatically closes the window when clicking the close button. Nevertheless closing the last JFrame does not result in a termination of your program, so you still need a WindowListener. Or you set setDefaultCloseOperation(EXIT_ON_CLOSE) which terminates the program, but you won’t be able to do any additional things, you could implement in a WindowListener.

// JFrame Example Code import java.awt.*; import javax.swing.*; public class JFrameExample { public static void main(String[] args) { WindowUtilities.setNativeLookAndFeel(); JFrame f = new JFrame("This is a test"); f.setSize(400, 150); Container content = f.getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); f.addWindowListener(new ExitListener()); f.setVisible(true); } }

// JApplet Example Code import java.awt.*; import javax.swing.*; public class JAppletExample extends JApplet { public void init() { WindowUtilities.setNativeLookAndFeel(); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); content.add(new JButton("Button 1")); content.add(new JButton("Button 2")); content.add(new JButton("Button 3")); } }

Page 3: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

1.3.3 JLabel

The JLabel is the Swing equivalent of the AWT Label. It has some need features like borders, images and HTML support. In order to use HTML, your String needs to be surrounded with <html></html> (case sensitive). In fact, the HTML support is a bit spotty, as e.g. a line break is done by <P> not <BR>.

1.3.4 JButton

The JButton is the Swing equivalent of the AWT Button. You can now add Icons to your Buttons, as well as HTML and Mnemonics (keyboard shortcuts) In order to add an Icon you need to pass the ImageIcon to the constructor or the setIcon method.

//JLable Example String labelText = "<html><FONT COLOR=WHITE>WHITE</FONT> and " + "<FONT COLOR=GRAY>GRAY</FONT> Text</html>"; JLabel coloredLabel = new JLabel(labelText, JLabel.CENTER); ... labelText = "<html><B>Bold</B> and <I>Italic</I> Text</html>"; JLabel boldLabel = new JLabel(labelText, JLabel.CENTER); labelText = "<html>The Applied Physics Laboratory is..." + "of the Johns Hopkins University." + "<P>" + ... "...</html>";

// WindowsListener with closing operation import java.awt.*; import java.awt.event.*; public class ExitListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } }

Page 4: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

//JButton Example import java.awt.*; import javax.swing.*; public class JButtons extends JFrame { public static void main(String[] args) { new JButtons(); } public JButtons() { super("Using JButton"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new FlowLayout()); JButton button1 = new JButton("Java"); content.add(button1); ImageIcon cup = new ImageIcon("images/cup.gif"); JButton button2 = new JButton(cup); content.add(button2); JButton button3 = new JButton("Java", cup); content.add(button3); JButton button4 = new JButton("Java", cup); button4.setHorizontalTextPosition (SwingConstants.LEFT); content.add(button4); pack(); setVisible(true); } }

Page 5: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136) 1.3.5 JPanel

The JPanel is the Swing equivalent of the AWT Panel. As well as all most other Components it got new features like borders and setting of preferred size and a LayoutManager. Borders can be created by using the BorderFactory: BorderFactory.createXxxBorder. Afterwards you need to call the setBorder() method of the JPanel in order to hand this new border to your JPanel.

//JPanel example code public class SixChoicePanel extends JPanel { public SixChoicePanel(String title, String[] buttonLabels) { super(new GridLayout(3, 2)); setBackground(Color.lightGray); setBorder(BorderFactory.createTitledBorder(title)); ButtonGroup group = new ButtonGroup(); JRadioButton option; int halfLength = buttonLabels.length/2; for(int i=0; i<halfLength; i++) { option = new JRadioButton(buttonLabels[i]); group.add(option); add(option); option = new JRadioButton(buttonLabels[i+halfLength]); group.add(option); add(option); } } }

Page 6: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136) 1.3.6 JSlider

The JSlider is the Swing equivalent of the AWT Slider. In Swing you can add tick marks and labels to the slider. 5 different constructors and a set of set Methods enables you to configure and modify the slider until it fits into your program.

(e.g.) Pictures: JSlider using a different look and feel

1.3.7 JColorChooser:

Another cool new feature of SWING is the JColorChooser. You can create Photoshop like ColorChooser right now ;). Simply call JColorChooser.showDialog giving the parent component, the title string and the initially-selected Color as parameter and “est Voilá”

//JSlider JSlider slider1 = new JSlider(); slider1.setBorder(...); content.add(slider1, BorderLayout.NORTH); JSlider slider2 = new JSlider(); slider2.setBorder(...); slider2.setMajorTickSpacing(20); slider2.setMinorTickSpacing(5); slider2.setPaintTicks(true); content.add(slider2, BorderLayout.CENTER); JSlider slider3 = new JSlider(); slider3.setBorder(...); slider3.setMajorTickSpacing(20); slider3.setMinorTickSpacing(5); slider3.setPaintTicks(true); slider3.setPaintLabels(true); content.add(slider3, BorderLayout.SOUTH);

Page 7: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

It returns the selected Color if OK was chosen or null if Cancel was clicked

1.3.8 Internal Frames:

Ever dreamed about doing your own Windows? In Windows you can have a lot of windows that are still some kind of organized. They are on a desktop that can hold windows. The same feature is now implemented in SWING. The MDI (Multiple Document Interface) is supported with the JDesktopPane (holder for the frames) and the JInternalFrame (basically like a JFrame, except that it only can stay inside a JDesktopPane). The main constructor looks like this:

– public JInternalFrame(String title,

boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable) and of course there is a set of useful methods. You need to have setSize() and setLocation() and in the end, everything might look like this:

// JColorChooser public void actionPerformed(ActionEvent e) { Color bgColor = JColorChooser.showDialog (this, "Choose Background Color", getBackground()); if (bgColor != null) getContentPane().setBackground(bgColor); }

Page 8: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

JDesktopPane desktop = new JDesktopPane(); desktop.setBackground(Color.white); content.add(desktop, BorderLayout.CENTER); setSize(450, 400); for(int i=0; i<5; i++) { JInternalFrame frame = new JInternalFrame(("Internal Frame " + i), true, true, true, true); frame.setLocation(i*50+10, i*50+10); frame.setSize(200, 150); frame.setBackground(Color.white); frame.setVisible(true); desktop.add(frame); frame.moveToFront(); } setVisible(true); } }

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JInternalFrames extends JFrame { public static void main(String[] args) { new JInternalFrames(); } public JInternalFrames() { super("Multiple Document Interface"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.white);

Page 9: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

1.3.9 JOptionPane

The JOptionPane is a very rich class with a bunch of options for displaying various kinds of dialog boxes. The component carries elements like buttons, icons and provides default symbols for common dialogs like:

• Input • Warning • Message • Confirm • Option

Like the other elements you can customize the static methods and the appearances of the dialog boxes like you wish, e.g. change the “look and feel”.

1.3.10 JToolBar

The JToolBar is one of the nice new things SWING provides for us which isn’t available in the AWT. Although it mainly acts like a JPanel, holding buttons, the main distinction is that JToolBar is dockable (or floatable). This option allows the toolbar to be dragged and dropped within a window and outside of the window. The JToolBar can dock e.g. on the left side of the window or can be dragged out of the window still working as a toolbar.

Page 10: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136) 1.3.11 JEditorPane

The next component is able to display and modify different types of formatted text and makes it possible to build up an environment e.g. for an editor (WYSWIG) or browser. In general the JEditorPane provides methods to write and read HTML and RTF text, but when we like to add optional functionalities the JEditorPane has to be provided with additional modules like the HyperLinkListener, or the extensions have to be linked with the class javax.swing.text.EditorKit.

1.3.12 Other Simple SWING Components JCheckBox

As you can probably imagine, the checkboxes in SWING can look significantly cooler than with the AWT. But focus on the spelling of JCheckBox whereas the AWT component is “Checkbox”.

Page 11: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

JRadioButton The JRadioButton uses a ButtonGroup to link the separated items.

JTextField The JTextField acts like any other ordinary text field of the AWT, except the fact that it can’t be used as a password text field. For this case SWING provides us with an additional class JPasswordField. JTextArea The JTextArea is especially interesting when you use it for displaying long text. If you want to scroll the text to make it somehow readable it can place JScrollPanes. JFileChooser

1.4 Summary of SWING Basics

• In general you only have to add a “J” in front of the class name of simple AWT components to port them into SWING components

• The Java look and feel is the default appearance of all components, but as you can imagine the native look and feel of your OS should be preferred. (So use SWING to get rid of the SUN GUI :-) )

• Never place your elements solely in your Window. Frames and applets use contentPanes to manage their components.

• As we mentioned most of the components have such nice features like borders and support the implementation of graphics.

• SWING supports “double buffering”1 on default • All in all there is a huge amount of new components to deal with.

Page 12: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

1.5 Advanced SWING

When we deal with complex and more sophisticated components and GUIs we have to take serious consideration on the architecture of our program especially on the encapsulation of our GUI. The architecture of Model-View-Controller (MVC) perfectly fits in this concept. It can be separated in three main principles: Custom Data Models You only have to be aware of telling the GUI how to access existing data instead of copying data from existing objects into the GUI. Custom cell renderers The GUI hasn’t to be able to change the value of objects, it only has to know how to build SWING components that represent each data value. Main applicable components

• JList • JTree • JTable

1.5.1 JList

The JList is another complex component which provides a list of data elements. You can select any number of items at the same time and since the java 1.4 you are also able to switch between the orientations of the data list. You can display the list of data vertically or horizontally.

Page 13: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136) 1.5.1.1 JList with a fixed set of choices

Build JList: pass strings to constructor The simplest way to use a JList is to supply an array of strings to the JList constructor. It cannot add or remove elements once the JList is created. String options = { "Option 1", ... , "Option N"}; JList optionList = new JList(options); Set visible rows Aferwards we call setVisibleRowCount and drop JList into the JScrollPane. optionList.setVisibleRowCount(4); JScrollPane optionPane = new JScrollPane(optionList); someContainer.add(optionPane); Handle events In the end we monitor the selections within the list and its values with an attached ListSelectionListener and use valueChanged.

public class JListSimpleExample extends JFrame { ... public JListSimpleExample() { super("Creating a Simple JList"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6" }; sampleJList = new JList(entries); sampleJList.setVisibleRowCount(4); sampleJList.addListSelectionListener (new ValueReporter()); JScrollPane listPane = new JScrollPane(sampleJList); ... }

Page 14: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

The output could look like this:

1.5.1.2 JList with a changeable set of choices

Instead of the simple JList the next JList should be aware of changing the representation of the list while displaying it on the screen. Therefore we have to create a somehow physical (origin) JList with a bunch of items and its representation, a model of a number of selected items.

private class ValueReporter implements ListSelectionListener { /** You get three events in many cases -- one for the * deselection of the originally selected entry, one * indicating the selection is moving, and one for the * selection of the new entry. In the first two cases, * getValueIsAdjusting returns true; thus, the test * below since only the third case is of interest. */ public void valueChanged(ListSelectionEvent event) { if (!event.getValueIsAdjusting()) { Object value = sampleJList.getSelectedValue(); if (value != null) { valueField.setText(value.toString()); } } } }

Page 15: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

Build JList: At first we create a DefaultListModel, an add our data, afterwards we pass it to our constructor. String choices = { "Choice 1", ... , "Choice N"}; DefaultListModel sampleModel = new DefaultListModel(); for(int i=0; i<choices.length; i++) { sampleModel.addElement(choices[i]); } JList optionList = new JList(sampleModel); Set visible rows and handle events We use the same GUI architecture as before and handle the occurring events as we did the last time. Add/remove elements As we mentioned, we have to take care of the original JList. When we remove or add elements from the JList to our representation we should only alter our model, we should never directly modifying the list.

private class ItemAdder implements ActionListener { /** Add an entry to the ListModel whenever the user * presses the button. Note that since the new entries * may be wider than the old ones (e.g., "Entry 10" vs. * "Entry 9"), you need to rerun the layout manager. * You need to do this <I>before</I> trying to scroll * to make the index visible. */ public void actionPerformed(ActionEvent event) { int index = sampleModel.getSize(); sampleModel.addElement("Entry " + (index+1)); ((JComponent)getContentPane()).revalidate(); sampleJList.setSelectedIndex(index); sampleJList.ensureIndexIsVisible(index); } } }

String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6" }; sampleModel = new DefaultListModel(); for(int i=0; i<entries.length; i++) { sampleModel.addElement(entries[i]); } sampleJList = new JList(sampleModel); sampleJList.setVisibleRowCount(4); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); JScrollPane listPane = new JScrollPane(sampleJList);

Page 16: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

A possible output could look like this picture:

1.5.1.3 JList with a Custom Data Model

The next example describes a JList implementation with a custom data model whereas the visualization and the handling of events is the same as before. All practices of adding or removing elements should also been made with the help of a mode.

Build JList

We assume that we have an existing data model which implements the ListModel interface and pass it to our constructor.

getElementAt � Gets an index and returns a specific data element getSize � Can tell our list how many entries it has addListDataListener � The user has the possibilities to add Listeners to monitor whether an items is selected or not. removeListDataListener � He also has the contrary opportunities

public class JavaLocationListModel implements ListModel { private JavaLocationCollection collection; public JavaLocationListModel (JavaLocationCollection collection) { this.collection = collection; } public Object getElementAt(int index) { return(collection.getLocations()[index]); } public int getSize() { return(collection.getLocations().length); } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} }

Page 17: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

The example output should look like this:

1.5.1.4 JList with a Custom Cell Renderer

As mentioned in beginning of the chapter, we can imagine to have a module which takes care of the visual representation of our JList or especially of its elements. That’s why we try to let SWING take care of drawing our elements instead of predetermining how our JList will do this. Therefore we let it specify the individual graphical component for each entry. We only have to attach a ListCellRenderer with

JavaLocationCollection collection = new JavaLocationCollection(); JavaLocationListModel listModel = new JavaLocationListModel(collection); JList sampleJList = new JList(listModel); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); content.add(sampleJList);

public class JavaLocationCollection { private static JavaLocation[] defaultLocations = { new JavaLocation("Belgium", "near Liege", "flags/belgium.gif"), new JavaLocation("Brazil", "near Salvador", "flags/brazil.gif"), new JavaLocation("Colombia", "near Bogota", "flags/colombia.gif"), ... }; ... }

Page 18: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

its getListCellRendererComponent method. It will determine the GUI component used for the representation of each cell. Arguments, to provide the special method with, are:

• JList: the list itself • Object: the value of the current cell • int: the index of the current cell • boolean: is the current cell selected? • boolean: does the current cell have focus?

The example would produce an output like this:

public class JavaLocationRenderer extends DefaultListCellRenderer { private Hashtable iconTable = new Hashtable(); public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean hasFocus) { JLabel label = (JLabel)super.getListCellRendererComponent (list,value,index,isSelected,hasFocus); if (value instanceof JavaLocation) { JavaLocation location = (JavaLocation)value; ImageIcon icon = (ImageIcon)iconTable.get(value); if (icon == null) { icon = new ImageIcon(location.getFlagFile()); iconTable.put(value, icon); } label.setIcon(icon); ... return(label); }}

Page 19: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

1.6 Summary of Advanced-SWING

• To build up a simple JList, you only have to pass an array of strings to the JList constructor

• Creating a simple changeable JList needs some more consideration. You have to pass a DefaultListModel to the JList constructor and use the model in your implementation for adding or removing elements from the visual representation.

• The construction of a custom data model needs a data structure and the implementation of ListModel interface. It also has to be passed to the JList constructor.

• The Custom cell renderer is nothing more than an assigned ListCellRenderer which provides us with a method that determines GUI components to be used for each cell

• Never directly change the JList. Use the model!!!

As you can imagine there are plenty examples out there for customizing or optimizing the look of your SWING components. Some of these resources can be explored from the following URLs:

SWING Demo (JFC SWING User Interface Toolkit) http://www.setupray.com/tech/Programing/java/demo/jfc/SwingSet2/SwingSet2.html Visual Index of SWING Components http://java.sun.com/docs/books/tutorial/uiswing/components/components.html Creating a GUI with JFC/SWING http://java.sun.com/docs/books/tutorial/uiswing/index.html http://www.theswingconnection.com When you are still looking for adventures and have time to play around you should analyse your .jar files: http://www.jgoodies.com/download/jpathreport/jpathreport.jnlp

Page 20: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

Networking in Java The used Networking slides are all provided by © Prof.Dr.Debora Weber-Wulff and the Text by © Prof.Dr. Lynn Andrea Stein

2.1 Quick Resume

If you can remember the last lectures in the first semester when we introduced “Networking in Java” for the first time, you probably know the slides and the following topic. Therefore there is a detailed lectures scribe existing in the internet on this topic and reading materials of Prof.Dr.Lynn Andrea Stein. Networking Lectures Scribes from the last semester by Janine Köhler and Christian Niermann http://de.geocities.com/jk_imi/info1/Koehler_Nierman_20012005.pdf Introduction To Interactive Programming by Prof.Dr.Lynn Andrea Stein http://www.cs101.org/ipij/pdf/net.pdf Nevertheless we try to sum up the main ideas of networking in the following.

2.1.1 Streams DEF.: A stream is a flowing sequence of characters.

There is a uniform interface in Java which controls the transmitting of information over a channel. Thereby we can distinguish three sorts of streams:

• communication across a network • between co-located entities • with persistent storage resources such as text files or disks

The communication between the entities works bitwise, that’s why the stream is like a sequence of values whereby in general no one knows how long the stream is. Java has four abstract stream classes, two each for input and output.

• input streams support the reading of values - InputStream - InputReader

• output streams support the writing of values - OutputStream - OutputWriter

All are in the package java.io and can be closed when no longer needed with close().

Page 21: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

The values in the input and output streams are bytes (8 bits). The values in the input reader and the output writer are characters (16 bits). Each of the abstract classes has subclasses with many useful additional methods. Most methods can potentially throw an exception, so be ready to catch!

2.1.2 Lector & Scribe

Since Reader and Writer are reserved Java words, we will be speaking of Lectors and Scribes. The lector mainly reads and the scribes should write in this model. 2.1.2.1 Scribes A Scribe is an object that keeps track of its output stream and, on (send) request, writes the object to be sent to the stream. It could offer a method like outStream.write( message ); Unfortunately there is something more to do besides writing messages. We have to clear the stream right now by calling the method flush() and not at point Java wants to do. A GenericScribeImpl would have to implement the interface Scribe and has to be provided with an output stream. If we don’t want our writing getting delayed, we could extend our class with the flush() method.

public interface Scribe { public void send( MessageType m ); }

TextField textField = new TextField(); Scribe scribe = new GenericScribeImpl(); public void actionPerformed ( ActionEvent ae ) { this.scribe.send ( this.textField.getText() ); }

public class GenericScribeImpl implements Scribe { private OutputStreamType outStream; public GenericScribeImpl ( OutputStreamType outStream ) { this.outStream = outStream; } public void send( MessageType m ) { outStream.write( m ); outStream.flush(); // (maybe) } }

Page 22: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

2.1.2.2 Lectors When we read an entity we have to make sure that we can store or evaluate it, because you will get something different when you read again. The lector should have something like this: inStream.read() Unfortunately we have to be concerned about this method. If a lector starts reading he won’t finish although there is nothing available. Therefore the blocking operation should have its own thread.

2.1.3 Sockets & Ports 2.1.3.1 Sockets

A socket is an abstraction of actual network connections and protocols. It contains two streams: one for input, one for output. To establish a socket connection, you need to run a program at each end (i.e., one program on each of the two computers that the socket will connect). more to read at http://en.wikipedia.org/wiki/Socket

public class Lector implements Animate{ private InputStreamType inStream; private AnimatorThread mover; public Lector( InputStreamType inStream ){ this.inStream = inStream; this.mover = new AnimatorThread( this ); this.mover.start(); } public void act(){ Console.println( "Lector: just read " + this.inStream.read().toString() ); } }

Page 23: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

2.1.3.2 Ports A place on another computer that we can connect to is called a port. It can't be found in the back of a computer, it is a virtual place to plug in a special kind of connection, called a socket. Ports are numbered. Values 1024 and less are reserved. For example a FTP connection uses Port 20 and 21 or the E-Mail protocol SMTP uses Port 25.

2.1.4 Server – Client communication

One of these programs "listens" for connection requests; this is called the server because it is providing the service of enabling socket connections. The server provides this service on a particular port of its machine. The server needs to know which port to be watching to see whether anyone is trying to connect. The other program is called the client, and it contacts the server to open a socket connection. The client program needs to specify what machine to contact, typically using the name of that machine, and also what port on that machine to try to connect to.

Besides the Server-Client communication there are several other architectures like • • hub-and-spoke • bottlenecks • peer to peer • hierarchical (DNS)

When we connect to a server on a particular port, we obtain a socket. You could ask from where we get it? But as often in Java we have to care about nothing except some fundamentals. The constructor takes care of this: new Socket( hostname, port ) // i.e. new Socket ( "imi.fhtw-berlin.de", 8080);

Page 24: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

When we are using a socket we have to accept a request from a client. For this reason ServerSocket has a method called accept(). Accept() waits until some program tries to connect to our port and returns its side of the connection. When a connection is already established it will block any request by throwing an IO exception.

A pretty cool implementation for a multithreading server or the general server-client communication has been made by Norbert Stein. It is available under the following links:

http://www.bundespokal.de/uni/netzwerkserver/MTServer.java http://www.bundespokal.de/uni/netzwerkserver/Server.java http://www.bundespokal.de/uni/netzwerkserver/Client.java

Sources:

3.1 Pictures Most of the pictures are made from the JFC SWING User Interface Toolkit, which can be found under http://www.theswingconnection.com/ or directly under http://www.setupray.com/tech/Programing/java/demo/jfc/SwingSet2/SwingSet2.html The other images are taken from the presentation SWING basics and Advanced SWING published by © 2001-2004 Marty Hall, Larry Brown: http://www.corewebprogramming.com Picture of a toolbar http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JToolBar.html Socket (©Dennis Mojado) Wikipedia http://en.wikipedia.org/wiki/Image:Sockets.jpg

3.2 Additional Information d.punkt Verlag http://www.dpunkt.de/java/Programmieren_mit_Java/

Networking Lectures Scribes from the last semester by Janine Köhler and Christian Niermann http://de.geocities.com/jk_imi/info1/Koehler_Nierman_20012005.pdf

public LectorScribe( Socket sock ) throws IOException { this( sock.getOutputStream(), sock.getInputStream() ); }

Page 25: 9. SWING & Networking

Lecture Scribe 2005-06-24 Martin Pomerenke (s0511072) Frank Wambutt (s0512136)

Introduction To Interactive Programming by Prof.Dr.Lynn Andrea Stein http://www.cs101.org/ipij/pdf/net.pdf

Input and Output Streams by the Open Journal Project http://journals.ecs.soton.ac.uk/java/tutorial/java/io/ ----------------------------------------------------------------------------------------------------------------- Note: 1double buffering When you try to animated objects on a screen you probably have noticed that there is a shimmer on the Applet field. The process of unloading the old image and loading the new one disturbs each other. To solve this conflict the new image is loaded on a temporary and invisible canvas and is placed on the Applet’s contentPane when it’s fully created. Therefore we can’t recognize the processes of removal and creation. This technique is called double buffering.