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
GUI 2: Inner classes & More Swing OOP tirgul No. 5 2009 Inner classes Suppose you write an applet, and you want your Applet subclass to contain some code to handle mouse events. A solution is to define an inner class — a class inside of your Applet subclass — that extends the MouseAdapter class. Inner classes can also be useful for event listeners that implement one or more interfaces directly. Example: public class MyClass extends Applet { ... someObject.addMouseListener(new MyAdapter()); ... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) { ...//Event listener implementation goes here... } } } Anonymous inner classes You can create an inner class without specifying a name public class MyClass extends Applet { ... someObject.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { ...//Event listener implementation goes here... } }); … } Nested & Inner classes • Static (nested) and Non-Static (inner) class OuterClass { ... static class NestedClass { ... } class InnerClass { ... } } • Access to nested/inner class from outside: OuterClass.NestedClass OuterClass out = …; out.InnerClass • Instantiation of nested/inner class from outside the outer class … nested =new OuterClass.NestedClass(…); out.InnerClass in = out.new InnerClass(…); Nested & Inner classes 2 • Nested/inner class hides outer class methods and fields. Access outer class methods/fields using OuterClass.staticMethod(…) or OuterClass.this.anyMethod(…) in case of inner class • Anonymous inner classes and local classes can access variables in the surrounding scope only if the variables are final void invokeAnon(final int number) { final String word = “hello”; someObject.pass(new Runnable() { public void run() { System.out.println(word.substring(number)); } }); } Nested & Inner classes 3 • Interfaces may have nested classes • Generics parameters of outer class can be used within inner classes • Nested enums are equivalent to static nested classes • Inner class cannot have static declarations in them • Nested class is treated just as any other class by the JVM, e.g. it is not loaded/initialized until used. • Inner class holds a strong reference to the enclosing instance More… and further more… Separating Data (model) from User Interface (view) Swing architecture, MVC • Swing architecture is rooted in the model-viewcontroller (MVC) design that dates back to Smalltalk. • MVC architecture calls for a visual application to be broken up into three separate parts: – model that represents the data for the application. – view that is the visual representation of that data. – controller that takes user input on the view and translates that to changes in the model. Model-View-Controller (MVC) UI: refresh View Data display Controller events refresh Data: User input manipulate Model Data model Swing’s Modified MVC • MVC split didn't work well in practical terms because the view and controller parts of a component required a tight coupling • So view and controller were collapsed into a single UI (user-interface) object, controlled by the “look-and-feel” Look and Feel • The architecture of Swing is designed so that you may change the "look and feel" (L&F) of your application's GUI – Look refers to the appearance of GUI widgets (JComponent-s) – Feel refers to the way the widgets behave • Swing's architecture enables multiple L&Fs by separating every JComponent into two distinct classes: a JComponent subclass and a corresponding ComponentUI subclass (delegate). Java L&F selection Sun's JRE provides the following L&Fs: • • • CrossPlatformLookAndFeel "Java L&F" (a.k.a "Metal") looks the same on all platforms. It is part of the Java API and is the default L&F. SystemLookAndFeel the L&F that is native to the system it is running on. The System L&F is determined at runtime, where the application asks the system to return the name of the appropriate L&F. … Windows Nimbus (new in Java 6) Metal Motif MV(C) Swing example: JList Creating the list listModel = new DefaultListModel(); JList list = new JList(listModel); listModel.addElement("Debbie Scott"); listModel.addElement("Scott Hommel"); listModel.addElement("Sharon Zakhour"); int index = list.getSelectedIndex(); listModel.remove(index); • Items are added \ removed from the model and not directly from the list. • There is no separate controller. JList - Model • Immutable: Vector / array (for static display) • Mutable: DefaultListModel (similar to vector) • Mutable: ListModel (interface): – – – – int getSize() Object getElementAt(int index) void addListDataListener(ListDataListener l) void removeListDataListener(ListDataListener l) JList ListDataListener ListModel JList - Model Partial implementation of ListModel: AbstractListModel ListModel bigData = new AbstractListModel() { public int getSize() { return Short.MAX_VALUE; } public Object getElementAt(int index) { return "Index " + index; } }; • This list model has about 2^16 elements. Enjoy scrolling. • Note: this is a static model: for remove / add some more code is needed. A class that listens to itself… import javax.swing.*; import java.awt.event.*; public class FileChooserDemo extends JPanel implements ActionListener { JFileChooser fc; } public FileChooserDemo() { fc = new JFileChooser(); JButton saveButton = new JButton("Save a File..."); saveButton.addActionListener(this); //… } The actionPerformed method public void actionPerformed(ActionEvent e) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); } if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); print("Opening: " + file.getName() ); } else { print("Open command cancelled by user."); } Dialogs and modality • A Dialog window is an independent subwindow meant to carry temporary notice apart from the main window. • Most Dialogs present an error message or warning to a user, but Dialogs can also present images, directory trees, progress bars and statuses, etc. • A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program. JOptionPane creates modal dialogs, to create a nonmodal Dialog, you must use the JDialog directly. Since Java 6, 4 types of modality are supported: none, document, application, toolkit. Simple dialogs JOptionPane.showMessageDialog( frame, "Eggs are not supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE); Object[] options = {"Yes, please", "No way!"}; int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?", "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options, //the titles of buttons options[0]); //default button title http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html Special dialogs - File Chooser //Create a file chooser final JFileChooser fc = new JFileChooser(); ... //In response to a button click: int returnVal = fc.showOpenDialog(aComponent); if (returnVal == JFileChooser.APPROVE_OPTION) File file = fc.getSelectedFile(); Custom Dialog • Our own class that extends JDialog, dialog.setVisible(true) • To intercept dialog closing: dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { … } }); • Dialog can call back to the component that opened it when, for example, Ok button was clicked • Or dialog can store input in a local variable and provide public access method to variable; when dialog is closed (setVisible(false)) the creator of the dialog checks the input values: Custom Dialog example public class CustomDialog extends JDialog implements ActionListener { CustomDialog dialog = new CustomDialog(this); final JTextField input; dialog.setVisible(true); … String in = dialog.getInput(); public CustomDialog(JFrame frame) { super(frame, true); //modal input = new JTextField(); Dialogs don’t need to be created every getContentPane().add(input); time they are needed. A dialog instance JButton okBut = new JButton("OK"); can be reused – stored in a local field, getContentPane().add(okBut); okBut.addActionListener(this); initialized first time it is needed and … reset/customized before it is shown } public void actionPerformed(ActionEvent e) { setVisible(false); } public String getInput() { return input.getText(); } http://zawoad.blogspot.com/2008/09/ showing-your-own-custom-dialog-boxin.html Binding & Property Change Events java.beans.PropertyChangeSupport, or even better for UI: javax.swing.event.SwingPropertyChangeSupport PropertyChangeSupport pc = new …(this); PropertyChangeListener listen1, listen2; … pc.addPropertyChangeListener(listen1); pc.addPropertyChangeListener(listen2); pc.firePropertyChange(“changed”, false, true); Listeners: public void propertyChange(PropertyChangeEvent evt) { …} Sun Tutorials, Swing Visual index Swing / AWT tutorial: http://java.sun.com/docs/books/tutorial/uiswi ng/ Swing Visual index : http://java.sun.com/docs/books/tutorial/uiswi ng/components/components.html Java, GUI, Internet Using Java for Rich Internet Applications (RIA) Java Applets, Java Plug-in, Java Web-Start (JNLP) Alternative GUI technologies in Java Eclipse Rich Client Platform (RCP) Google Web Toolkit (GWT) Sun JavaFX … Web-based UI in Java Servlet, JSP, JSF