320 likes | 496 Views
File Reading and Writing. import java.io.*; public class ReadWriteTextFile { static public void main(String args[]) throws IOException { try { BufferedReader input = new BufferedReader(new FileReader(“a.txt"));
E N D
File Reading and Writing import java.io.*; public class ReadWriteTextFile { static public void main(String args[]) throws IOException { try { BufferedReader input = new BufferedReader(new FileReader(“a.txt")); BufferedWriter output = new BufferedWriter(new FileWriter("b.txt")); try { String line = null; while (( line = input.readLine()) != null){ System.out.println(line); output.write( line + "\n"); } } finally { input.close(); output.close(); } } catch (IOException ex){ ex.printStackTrace(); } }}
import java.awt.*; import java.awt.event.*; import javax.swing.*; class TestMouse extends JFrame implements MouseListener { public TestMouse() { this.addMouseListener(this); } public void mouseClicked(MouseEvent e) { javax.swing.JOptionPane.showMessageDialog(this, "Mouse button clicked"); } public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseReleased(MouseEvent e){} public static void main(String[] args) { TestMouse frame = new TestMouse(); frame.pack(); frame.setSize(300,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Strategy Pattern Context: • A class can benefit from different variants for an algorithm • Clients sometimes want to replace standard algorithms with custom versions
Solution • Define an interface type that is an abstraction for the algorithm • Actual strategy classes realize this interface type. • Clients can supply strategy objects • Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object
public Telephone() { JPanel speakerPanel = new JPanel(); speakerPanel.setLayout(new BorderLayout()); speakerPanel.add(new JLabel("Speaker:"), BorderLayout.NORTH); speakerField = new JTextArea(10, 25); speakerPanel.add(speakerField, BorderLayout.CENTER); String keyLabels = "123456789*0#"; JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3)); for (int i = 0; i < keyLabels.length(); i++) { final String label = keyLabels.substring(i, i + 1); JButton keyButton = new JButton(label); keyPanel.add(keyButton); keyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //connect.dial(label); } }); }
final JTextArea microphoneField = new JTextArea(10,25); JButton speechButton = new JButton("Send speech"); JButton hangupButton = new JButton("Hangup"); hangupButton.addActionListener(new ActionListener() { }); JPanel buttonPanel = new JPanel(); buttonPanel.add(speechButton); buttonPanel.add(hangupButton); JPanel microphonePanel = new JPanel(); microphonePanel.setLayout(new BorderLayout()); microphonePanel.add(new JLabel("Microphone:"), BorderLayout.NORTH); microphonePanel.add(microphoneField, BorderLayout.CENTER); microphonePanel.add(buttonPanel, BorderLayout.SOUTH); JFrame frame = new JFrame(); rame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(speakerPanel, BorderLayout.NORTH); frame.add(keyPanel, BorderLayout.CENTER); frame.add(microphonePanel, BorderLayout.SOUTH);
Creating a Custom Layout Manager • Layout manager determines how components are arranged/displayed in a container • Can determine your own layout pattern by implementing the LayoutManager interface
LayoutManager interface public interface LayoutManager { void layoutContainer(Container parent); Dimension minimumLayoutSize(Container parent); Dimension preferredLayoutSize(Container parent); void addLayoutComponent(String name, Component comp); void removeLayoutComponent(Component comp); }
LayoutManager methods • minimumLayoutSize() and preferredLayoutSize() determine the minimum and default size of the container when components are laid out • Start with preferredLayoutSize - determine the height and width of each component, and use the combined sizes to determine how large window must be • Can implement minimumLayoutSize() by just having it call preferredLayoutSize()
LayoutManager methods • layoutContainer() lays out components by setting position and size of each • Method computes positions of each component then calls setBounds to put each component in its correct location
Composite Pattern • Context • Primitive objects can be combined to composite objects • Clients treat a composite object as a primitive object
Composite Pattern • Solution • Define an interface type that is an abstraction for the primitive objects • Composite object collects primitive objects • Composite and primitive classes implement same interface type. • When implementing a method from the interface type, the composite class applies the method to its primitive objects and combines the results
Containers and Components • Containers collect GUI components • Sometimes, want to add a container to another container • Container should be a component • Composite design pattern • Composite methods typically invoke component methods • E.g. Container.getPreferredSize invokes getPreferredSize of components
Design name Primitive Composite Leaf method() Actual name Component Container JButton, JPanel, JOptionPane, or other class with no children Component method such as getPreferredSize() AWT components - composite
Decorator Pattern • Context • Component objects can be decorated (visually or behaviorally enhanced) • The decorated object can be used in the same way as the undecorated object • The component class does not want to take on the responsibility of the decoration • There may be an open-ended set of possible decorations
Decorator Pattern • Solution • Define an interface type that is an abstraction for the component • Concrete component classes realize this interface type. • Decorator classes also realize this interface type.
Decorator Pattern • Solution • A decorator object manages the component object that it decorates • When implementing a method from the component interface type, the decorator class applies the method to the decorated component and combines the result with the effect of the decoration.
Scroll Panes & Scroll Bars • Scroll bars useful when a component contains more information than can be displayed in available space • Add functionality to underlying component • JScrollPane decorates a component and is itself a component
JScrollPane • Scroll bars can be attached to components • Approach #1: Component class can turn on scroll bars • Approach #2: Scroll bars can surround component JScrollPane pane = new JScrollPane(component); • Swing uses approach #2 - JScrollPane is again a component
Design name: Component ConcreteComponent Decorator method() Actual name: Component JTextArea JScrollPane paint() or other method of Component Decorator Pattern: Scroll Bars
import javax.swing.*; public class ScrollTest { public static void main(String args[]) { JFrame f = new JFrame(); JTextArea area = new JTextArea(10,25); JScrollPane scroller = new JScrollPane(area); f.add(scroller); f.setSize(300,400); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
I/O stream filters as decorators • BufferedReader takes a Reader and adds buffering • Result is another Reader: Decorator pattern InputStreamReader r = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(r); • Many other decorators in stream library, e.g. PrintWriter
Design name: Component ConcreteComponent Decorator method() Actual name: Reader InputStreamReader BufferedReader read() Decorator pattern: I/O filters
How to Recognize Patterns • Look at intent of pattern: e.g. COMPOSITE has different intent than DECORATOR • Remember common uses (e.g. STRATEGY for layout managers) • Use context and solution as "litmus test"
Recognizing Patterns • Not everything that is strategic is an example of STRATEGY pattern • Context must want to use different variants of an algorithm • Must be an interface type that is an abstraction of the algorithm; concrete strategy classes must implement the interface • Client supplies object of strategy class to context class; context class uses strategy object to invoke algorithm
Litmus test - example • Can add border to Swing component Border b = new EtchedBorder() component.setBorder(b); • Undeniably decorative • Is it an example of DECORATOR?
Litmus test - example • Component objects can be decorated (visually or behaviorally enhanced): PASS • The decorated object can be used in the same way as the undecorated object: PASS • The component class does not want to take on the responsibility of the decoration: FAIL--the component class has setBorder method