Presentation is loading. Please wait.

Presentation is loading. Please wait.

1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 9: Swing Components.

Similar presentations


Presentation on theme: "1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 9: Swing Components."— Presentation transcript:

1 1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 9: Swing Components

2 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Widget Week! Look at the most common GUI components – see what they do – see how they work High-level goal: Get prepared to build a real interface!

3 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Component hierarchy Top-level Containers (frame, dialog, applet, …) Intermediate Containers (panel, scroll pane, …) Atomic Components (button, list, menu, …) javax.swing. JComponent java.awt. Window today’s focus

4 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Lists Storage for a list of items – typically text, or textual representations of complex objects (e.g., 9:00pm) – could also be icons Selection – single selection – single interval – multiple interval

5 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 List View vs. Data Lists have a common interface for dealing with the sequence of data – allows data to be shared across lists, tables, etc. ListModel interface – defines methods for dealing with lists – index in [0, size-1] Object getElementAt (int index) int getSize (); void addListDataListener (ListDataListener l); JList (list view) ListModel (list data)

6 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JList Basic constructor – sets a basic list model that is unchangeable (no insertions/deletions after creation) – model created automatically, and you can access it if you want... String[] data = {"one", "two", "three", "four"}; JList dataList = new JList (data); for (int i = 0; i < dataList.getModel().getSize(); i++) { System.out.println (dataList.getModel().getElementAt(i)); }

7 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JList Constructor with more powerful list model – first, create DefaultListModel allows insertions/deletions at any time – then, create JList based on this list model list = new JList (listModel); listModel = new DefaultListModel(); listModel.addElement (”Thing1"); listModel.addElement (”Thing2"); listModel.addElement (”Thing3"); listModel.addElement (”Thing4"); … listModel.remove (index);

8 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JList List selection – complex class ListSelectionModel – handles selection intervals, etc. What we’ll need to know… list = new JList (listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); (ListSelectionModel.SINGLE_INTERVAL_SELECTION); (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

9 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JList Handling selection events (on the JList view) … list.addListSelectionListener (new MyListSelectionListener()); … public class MyListSelectionListener implements ListSelectionListener { public void valueChanged (ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { // No selection } else { // Selection, update text field. } // What you might use in the above functions… listModel.addElement (…); listModel.insertElementAt (…); listModel.remove (…);

10 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tables Close cousins to our good friends, Lists Typical case – two-dimensional grid uneditable to display tabular information editable to manage tabular information – usually alpha-numeric text But many possibilities...

11 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Chasing toddlers", new Integer(2), new Boolean(false)}, {"Mark", "Andrews", "Speed reading", new Integer(20), new Boolean(true)}, {"Angela", "Lih", "Teaching high school", new Integer(4), new Boolean(false)} }; String[] columnNames = {"First Name”, "Last Name”, "Sport”, "# of Years”, … } JTable table = new JTable(data, columnNames); Basic table Simple example Problems: all cells are editable Strings, full array is pre-initialized

12 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table model As for lists, tables have Model vs. View Create model first, then create view with this model Table models typically extend AbstractTableModel (next slide…) MyTableModel myModel = new MyTableModel(); JTable table = new JTable(myModel);

13 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 TableDemo.java example class MyTableModel extends AbstractTableModel { final String[] columnNames =...//same as before... final Object[][] data =...//same as before... public int getColumnCount() { return columnNames.length; }... public Object getValueAt(int row, int col) { return data[row][col]; } public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. if (col < 2) { return false; } else { return true; }... Table model

14 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table view Resizing columns TableColumn column = null; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //sport column is bigger } else { column.setPreferredWidth(50); }

15 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table cells Cell renderer – used to draw all cells, shared by cell type Boolean -- rendered with a check box Number -- rendered by a right-aligned label ImageIcon -- rendered by a centered label Object -- rendered by a label w/ the object's string Cell editor – takes over when user edits the cell Example: Integer object in cell – renderer: JLabel, right-aligned – editor: JTextField, right-aligned

16 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table cells Different editors in one table Text FieldCombo BoxCheck Box

17 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table cells Color chooser as editor

18 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table data manager Provide way of manipulating data in layer between model and view One important, common use: Sorting! CLICK!

19 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Trees Lots of data forms nicely into a hierarchy – tree structure: every node has 1 parent (except root) – e.g., directories & files, company management structures, Swing components! Nice to have a convenient, standard way of storing and viewing

20 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing Trees Basic structure – root node – branch nodes – leaf nodes Yet again… Model vs. View – model = hierarchy of data/information – view = vertical list of currently visible nodes that can be expanded or collapsed

21 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree model Constructing the model – construct root node, as DefaultMutableTreeNode – construct other nodes & add to parent node – finally, construct model with root node DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); category = new DefaultMutableTreeNode ("Books for Java Programmers"); top.add(category); book = new DefaultMutableTreeNode ("The Java Tutorial: Object-Oriented”); category.add(book); treeModel = new DefaultTreeModel(rootNode); can be any Object!

22 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree view Create a JTree with the model – often good idea to add scrollbars DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");... >... JTree tree = new JTree(top); JScrollPane treeView = new JScrollPane(tree);

23 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree view Selection based on “paths” – path of nodes from root to node (leaf or branch) – in Swing: TreePath class stores path as array – or, method direct to bottom-most node… tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);... DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

24 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree view Handling selection events tree.addTreeSelectionListener (new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; if (node.isLeaf()) { Object nodeInfo = node.getUserObject(); BookInfo book = (BookInfo)nodeInfo; displayURL(book.bookURL); } else { displayURL(helpURL); } }); handle branchhandle leaf

25 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree extras Changing view properties – node connectors – different renderers

26 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Useful things to know ComponentsTo Check/Set StateTo Handle Events JButton ActionListener JCheckBox void setSelected (boolean) boolean isSelected () ItemListener JRadioButton void setSelected (boolean) boolean isSelected () ActionListener JComboBox void setSelectedIndex (int) Object getSelectedItem () ActionListener JSlider void setValue(int) int getValue() ChangeListener JList void setSelectedIndex (int) int getSelectedIndex () ListSelectionListener DefaultListModel void addElement (Object) void insertElementAt (Object,int) void remove (int) Object getElementAt (int) int getSize () ListDataListener [created for you if you use JList constructor passing list model] JTextField void setText (String) String getText () ActionListener

27 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menus A great GUI development! (Apple Lisa) Fit lots of functionality into a small space – requires overlapping & restoring of graphics Have become more standardized, more hierarchical, & just plain bigger

28 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing Menu Components Within the component hierarchy, can contain several types of components

29 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu Bar Represents the bar of top-level items Creating a menu bar Setting the bar in a frame, applet, etc. JMenuBar () JMenu add (JMenu) void setJMenuBar(JMenuBar) JMenuBar getJMenuBar()

30 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu Any item — in a menu bar or menu — that displays more options Creating the menu Adding items (options) to the menu JMenu () JMenu (String) JMenuItem add (JMenuItem) JMenuItem add (String) void addSeparator () JMenuItem insert (JMenuItem, int) void insert (String, int) void insertSeparator(int)

31 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu Items Terminal components of the menu, with actions associated with them Creating menu items (w/ Strings, Icons) JMenuItem() JMenuItem(S) JMenuItem(I) JMenuItem(S,I) JCheckBoxMenuItem() JCheckBoxMenuItem(S) JCheckBoxMenuItem(I) JCheckBoxMenuItem(S,I) JRadioButtonMenuItem() JRadioButtonMenuItem(S) JRadioButtonMenuItem(I) JRadioButtonMenuItem(S,I)

32 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu Items How do you handle menu item events? (this is, when the item is selected) Remember, menu items are buttons — treat them that way! So then… – JMenuItem --> action listener – JRadioButtonMenuItem --> action listener – JCheckBoxMenuItem --> item listener

33 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu Items Adding keys to items – Mnemonics : keys that navigate menus, only visible components – Accelerators : keys that provide shortcuts directly to function, visible or not void setAccelerator (KeyStroke) void setMnemonic (int)

34 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 MenuDemo.java menuBar = new JMenuBar(); setJMenuBar(menuBar); menu = new JMenu("A Menu"); menu.setMnemonic(KeyEvent.VK_A); menu.getAccessibleContext().setAccessibleDescription( "The only menu in this program that has menu items"); menuBar.add(menu); menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1, ActionEvent.ALT_MASK)); menuItem.getAccessibleContext().setAccessibleDescription( "This doesn't really do anything"); menu.add(menuItem); menuItem = new JMenuItem("Both text and icon", new ImageIcon("images/middle.gif")); menuItem.setMnemonic(KeyEvent.VK_B); menu.add(menuItem); create menu bar create menu, with “A” mnemonic more menu items …

35 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 MenuDemo.java menu.addSeparator(); ButtonGroup group = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem ("A radio button menu item"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); group.add(rbMenuItem); menu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem("Another one"); rbMenuItem.setMnemonic(KeyEvent.VK_O); group.add(rbMenuItem); menu.add(rbMenuItem); menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem ("A check box menu item"); cbMenuItem.setMnemonic(KeyEvent.VK_C); menu.add(cbMenuItem); add separator create radio button menu items w/ button group create check box menu items

36 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 MenuDemo.java submenu = new JMenu("A submenu"); submenu.setMnemonic(KeyEvent.VK_S); menuItem = new JMenuItem("An item in the submenu"); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_2, ActionEvent.ALT_MASK)); submenu.add(menuItem); menuItem = new JMenuItem("Another item"); submenu.add(menuItem); menu.add(submenu); menu = new JMenu("Another Menu"); menu.setMnemonic(KeyEvent.VK_N); menu.getAccessibleContext().setAccessibleDescription( "This menu does nothing"); menuBar.add(menu); add submenu add items to submenu add second menu in bar (no items!)

37 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Pop-Up Menus Menu that can be brought up anywhere on a “registered” component (frame, button, …) Menus actually use pop-ups to show items!

38 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Menu layout ?!? You can even (gasp!) lay out the menu – putting glue in the menu bar (bewarned!) – changing the layout of the menu bar / items (please don’t try this at home)

39 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text components GUIs may be graphical, but TEXT still forms the core of many interactions – reading text: help manuals, web pages, … – writing text: word processing, email, … Some text comes in short bursts, some comes in long passages

40 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing text components Text controls – limited amount of information, then action (?) Plain text areas – unformatted text of unlimited length Styled text areas – display, edit text of many styles

41 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text component components What does a text component consist of? – model / document : stores textual content – view : displays text – controller / “editor kit” : implements editing capabilities for read/write – keymap : binds keys to actions – support for undo/redo, carets

42 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text model / document Text components = View Document = Model The document... – contains text in logical structure (paragraphs, styles, etc.) – provides low-level support for editing text with insert and remove – notifies document & undo listeners of changes – manages position of focus (e.g., cursor) – allows retrieval of text information / properties

43 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text editor kit Functionality for editing - inserting, deleting, cutting, pasting, … – e.g., move to next word/para/page, select … – stored as Swing “Action”s All text components have them, but you can’t always get at them – e.g., text fields Built-in Swing editors – DefaultEditorKit : plain text – HTMLEditorKit : HTML – RTFEditorKit : RTF

44 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text keymaps Associate keys with actions – classes: Keystroke --> Action – e.g., “Cmd-C” --> “copy” By default, text components use JTextComponent.DEFAULT_KEYMAP

45 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text component example

46 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text & password fields Text field Password field JTextField textField = new JTextField(10); textField.setActionCommand(textFieldString); textField.addActionListener(this); public void actionPerformed(ActionEvent e) { String prefix = "You typed \""; if (e.getActionCommand().equals(textFieldString)) { JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\""); } else { JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\""); } JPasswordField passwordField = new JPasswordField(10); passwordField.setActionCommand(passwordFieldString); passwordField.addActionListener(this);

47 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Plain text area Create & initialize (if desired) Set properties (note single font/style) JTextArea textArea = new JTextArea( "This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." ); textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true);

48 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Plain text area Setting scrollbars – we haven’t really done this yet, but… – use an intermediate-level “scroll pane” JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250)); areaScrollPane.setBorder(...create border...);

49 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Styled text area Creating an uneditable “editor pane” (huh?) linked to a URL page JEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false);...//create a URL object for the TextSamplerDemoHelp.html file... try { editorPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); }

50 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Validated text field Enforce a particular format on text – e.g., for numbers, dates, times, etc. Two types of validation – action-validated : check only on action event (i.e., user presses Return) – change-validated : check continually, thus never allowing invalid data

51 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Validated text field TextFieldDemo.java NumberFormat moneyFormat = NumberFormat.getNumberInstance(); amountField = new DecimalField(amount, 10, moneyFormat); NumberFormat percentFormat = NumberFormat.getNumberInstance(); percentFormat.setMinimumFractionDigits(3); rateField = new DecimalField(rate, 10, percentFormat); numPeriodsField = new WholeNumberField(numPeriods, 10); DecimalFormat paymentFormat = (DecimalFormat)NumberFormat.getNumberInstance(); paymentFormat.setMaximumFractionDigits(2); paymentFormat.setNegativePrefix("("); paymentFormat.setNegativeSuffix(")"); paymentField = new DecimalField(payment, 10, paymentFormat);

52 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Validated text field — Side note WholeNumberField, subclass of TextField What might its implementation look like? protected Document createDefaultModel() { return new WholeNumberDocument(); } protected class WholeNumberDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) … { char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; for (int i = 0; i < result.length; i++) { if (Character.isDigit(source[i])) result[j++] = source[i]; else { toolkit.beep(); System.err.println("insertString: " + source[i]); } super.insertString(offs, new String(result, 0, j), a); }

53 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Panels As we’ve seen… – don’t really do anything – logical groupings for layouts, with optional borders / labels

54 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Panel borders Various types of borders

55 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Scroll panes Sometimes, components are too big to display in whole So add scrollbars!

56 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JScrollPane Constructors Scrollbar policies Note: typically don’t create scrollbars and viewport — all taken care of! JScrollPane(Component view) JScrollPane(Component view, int vsbPolicy, int hsbPolicy) HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_NEVER VERTICAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_ALWAYS VERTICAL_SCROLLBAR_NEVER

57 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Scroll pane features Customizing row/column headers Swing Rule components

58 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Scroll pane features Being “scrolling-savvy” – must implement Scrollable interface getScrollableBlockIncrement getScrollableUnitIncrement getPreferredScrollableViewportSize getScrollableTracksViewportHeight getScrollableTracksViewportWidth e.g. lists tables trees text

59 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Finally! We’re done the Swing components! Or at least the ones we’ll be looking at. Still ones we haven’t discussed, like … – JApplet top-level container – JLayeredPane intermediate container – etc. Make use of Sun’s Java Swing web site and any of numerous Java & Swing books


Download ppt "1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 9: Swing Components."

Similar presentations


Ads by Google