Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 5: 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 Buttons Something that invokes an action/command or changes system state – “OK” / “Cancel” – “New Folder” – File type: “Word 98” Visual design based on real-world buttons – physical mouse click also resembles button push! (the power of metaphors…)

5 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Buttons AbstractButton = abstract parent class – JButton – JCheckBox – JRadioButton – JMenuItem – and more… Side note: AbstractButton is an abstract class, not an interface

6 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 All Buttons Can contain both text and icon What’s an icon? ImageIcon leftButtonIcon = new ImageIcon ("images/right.gif");

7 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 All Buttons Placing text in the buttons Enabling / disabling buttons (important!!) b.setEnabled(true); (false); b.setHorizontalTextPosition(AbstractButton.CENTER); (AbstractButton.LEFT); (AbstractButton.RIGHT); b.setVerticalTextPosition(AbstractButton.CENTER); (AbstractButton.TOP); (AbstractButton.BOTTOM);

8 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 All Buttons Noting the “Action Command” – string that denotes what the button does – can be used in handling events b3.setActionCommand (“disable”); public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getActionCommand().equals("disable")) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); }

9 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 All Buttons Associating keys Attaching “tool tips” b1.setMnemonic (KeyEvent.VK_D); b2.setMnemonic (KeyEvent.VK_M); b3.setMnemonic (KeyEvent.VK_E); b1.setToolTipText ("Click this button to disable the middle button."); b2.setToolTipText ("This middle button does nothing when you click it."); b3.setToolTipText ("Click this button to enable the middle button.");

10 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Our old friend... Constructors JButton ()// Creates a plain button, no icon or text JButton (Icon icon)// Creates a button with an icon. JButton (String text)// Creates a button with text. JButton (String text, Icon icon)// Creates a button with initial text and an icon

11 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Setting the default button (for “Return” key) getRootPane().setDefaultButton (setButton);

12 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Using HTML in the button label (Only later versions! >= JDK 1.2.1 ) b1 = new Jbutton (" D isable middle button ", leftButtonIcon); b2 = new JButton(" Middle button ", middleButtonIcon); b3 = new JButton(" E nable middle button ", rightButtonIcon);

13 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Handling events … button. addActionListener (new MyActionListener ()); … class MyActionListener implements ActionListener { public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals("disable")) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); }

14 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Toggle buttons JToggleButton with subclasses – JCheckBox – JRadioButton Three kinds of events Checking state Click press:ChangeEvent// button pressed Click release:ChangeEvent// button selected ItemEvent// item state changed ChangeEvent// button released ActionEvent// full button press if (button.isSelected()) … good for radio button! good for check box!

15 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JCheckBox Check box: on/off toggle, each box independent of all others

16 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JCheckBox ItemListener interface Handling events for a JCheckBox… – (next slide) void itemStateChanged(ItemEvent e) Invoked when an item has been selected or deselected.

17 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 CheckBoxListener myListener = new CheckBoxListener(); chinButton.addItemListener(myListener); glassesButton.addItemListener(myListener); hairButton.addItemListener(myListener); teethButton.addItemListener(myListener);... class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) {... Object source = e.getItemSelectable(); if (source == chinButton) { //...make a note of it... } else if (source == glassesButton) { //...make a note of it... } else... if (e.getStateChange() == ItemEvent.DESELECTED) //...make a note of it... picture.setIcon(/* new icon */); } JCheckBox

18 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JRadioButton Radio button: on/off toggle, but only one of a group of buttons can be selected

19 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JRadioButton birdButton = new JRadioButton(birdString); birdButton.setSelected(true); JRadioButton catButton = new JRadioButton(catString); JRadioButton dogButton = new JRadioButton(dogString); JRadioButton rabbitButton = new JRadioButton(rabbitString); JRadioButton pigButton = new JRadioButton(pigString); … ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton);... > JRadioButton group buttons to handle selection one selected

20 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Handling events RadioListener myListener = new RadioListener(); birdButton.addActionListener(myListener); catButton.addActionListener(myListener); dogButton.addActionListener(myListener); rabbitButton.addActionListener(myListener); pigButton.addActionListener(myListener);... class RadioListener implements ActionListener... { public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif")); } JRadioButton

21 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Combination (Combo) Box Select from a fixed list of items – typically, a not-so-large list – typically, a sorted list (easy to find items)

22 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JComboBox String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; // Create the combo box, select item at index 4 // Indices start at 0, so 4 specifies the pig JComboBox petList = new JComboBox(petStrings); petList.setSelectedIndex(4); … petList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); String petName = (String) cb.getSelectedItem(); picture.setIcon(new ImageIcon("images/" + petName + ".gif")); } }); Note: Listener only needed if you need to do something for each action!

23 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Text Field Editable, single-line field for typing text Keypresses, deletions handled for you! You can also monitor changes (e.g., keypresses) and take action as they happen Special text fields – password fields (“”) – validated fields (e.g, “$7.95”)

24 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JTextField Constructors Setting / getting text — the obvious... JTextField()// Constructs a new TextField. JTextField(int columns)// Constructs a new empty TextField with the specified number of columns. JTextField(String text)// Constructs a new TextField initialized with the specified text. JTextField(String text, int columns)// Constructs a new TextField initialized with the specified text and columns. textField.getText (); textField.setText (text);

25 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Handling events like usual… … textField.addActionListener(new MyTextListener ());... class MyTextListener implements ActionListener... { public void actionPerformed(ActionEvent e) { String text = textField.getText (); > } JTextField

26 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Sliders Allow selection from a range of discrete options – though look & feel is continuous! Typical parts – slider itself – labels – “tick marks”

27 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JSlider Constructors Example JSlider() Creates a horizontal slider with the range 0 to 100 and an intitial value of 50. JSlider(int orientation) Creates a slider using the specified orientation with the range 0 to 100 and an initial value of 50. JSlider(int min, int max) Creates a horizontal slider using the specified min and max with an initial value of 50. JSlider(int min, int max, int value) Creates a horizontal slider using the specified min, max and value. JSlider(int orientation, int min, int max, int value) Creates a slider with the specified orientation and the specified mimimum, maximum, and initial values. JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, 0, 30, FPS_INIT); framesPerSecond.setMajorTickSpacing(10); framesPerSecond.setMinorTickSpacing(1); framesPerSecond.setPaintTicks(true); framesPerSecond.setPaintLabels(true);

28 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JSlider ChangeListener interface Handling events for a JSlider void stateChanged(ChangeEvent) Called when the listened-to component changes state. framesPerSecond.addChangeListener(new SliderListener()); … class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue();... } may or may not want this

29 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Labels Present text or icons on the screen No actions associated with them

30 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JLabel Constructors Example JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(Icon image) Creates a JLabel instance with the specified image. JLabel(Icon image, int horizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(String text, Icon icon, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, int horizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. label1 = new JLabel(“Image and Text”, icon, JLabel.CENTER); label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER);

31 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JLabel Using HTML in labels (Only later versions! >= JDK 1.2.1 )

32 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tool Tips When user’s mouse pointer pauses over an item, “tool tips” provide further information – implicit assumption: user may be considering this item as an option, but isn’t quite so sure…

33 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JToolTip You won’t usually deal directly with JToolTip — don’t need to construct, etc. Instead, just create tip text as follows: Works for any JComponent !! b1.setToolTipText("Click this button to disable the middle button."); b2.setToolTipText("This middle button does nothing when you click it."); b3.setToolTipText("Click this button to enable the middle button.");

34 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

35 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)

36 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)); }

37 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);

38 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);

39 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 (…);

40 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...

41 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

42 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);

43 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

44 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); }

45 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

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

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

48 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!

49 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

50 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

51 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!

52 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);

53 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();

54 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

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

56 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


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

Similar presentations


Ads by Google