Presentation is loading. Please wait.

Presentation is loading. Please wait.

1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 8: Layout Management.

Similar presentations


Presentation on theme: "1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 8: Layout Management."— Presentation transcript:

1 1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 8: Layout Management

2 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Overview Last week… – GUI design – Event Driven Programming This week… – Swing Time! – Building the GUI components, layout – Handling GUI events

3 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Building a Swing GUI Consider the following “SwingApplication” (courtesy of Sun’s Java Swing Tutorial) Every app defines a hierarchy of components – “component” = “widget”! Containment Relationship

4 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Model-View-Controller Architecture All three elements are interdependent! The Layout controls the View Model View Controller Component User Conduit

5 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 The Model Is The Program Models are your internal representation of the state of the program. Use any data structure you want, its up to the Component to visualize it. You program the Component to display it the way you want! You program the Model to store the data (hopefully efficiently) the way you want!

6 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Top-level containers JFrameJDialogJApplet

7 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components General-purpose containers JSplitPane JToolbar JScrollPane JPanel JTabbedPane

8 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Special-purpose containers JLayeredPane JInternalFrame

9 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JavaDocs look at Swing! JavaDocs are a Great Tool! Program with the window open, it will save you time and headaches. Swing Components have MANY options and methods available. Lets take a look at the JavaDocs for Java and for Swing!

10 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Basic Controls JButton JComboBox JList JMenu JSlider JTextField

11 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Uneditable displays JLabel JProgressBar JToolTip

12 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Swing components Editable displays JColorChooserJFileChooser JTreeJTextJTable

13 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Creating components Just call the constructors! All we’ve done is create the structures Still need to: – add components to container, w/ layout – display container frame = new JFrame (...); button = new JButton (...); label = new JLabel (...); pane = new JPanel (); … Use the JavaDocs!

14 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

15 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…)

16 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

17 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");

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

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

20 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.");

21 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

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

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

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

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

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

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

28 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

29 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

30 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

31 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

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

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

34 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”)

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

36 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

37 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”

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

39 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

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

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

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

43 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers Set the layout manager and add components For top-level containers as root frames: – add components to Content Pane – add components to intermediate components frame.getContentPane().add (button); JPanel panel = new Jpanel (); panel.add (button); // … and more… frame.getContentPane().add (panel);

44 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers BorderLayout (the default) JPanel pane = new JPanel(); pane.setLayout (new BorderLayout()); // not really needed … pane.add (buttonNorth, BorderLayout.NORTH); pane.add (buttonCenter, BorderLayout.CENTER); …

45 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers BorderLayout (cont.) – can’t add twice in the same place – can add spacing with the constructor JPanel pane = new JPanel(); pane.setLayout (new BorderLayout (5, 20)); // xGap, yGap contentPane.add (buttonNorth1, BorderLayout.NORTH); contentPane.add (buttonNorth2, BorderLayout.NORTH); // this second add() puts the second button on top of the first!

46 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers BoxLayout: across or up/down private void addAButton(String text, JPanel container) { JButton button = new JButton(text); button.setAlignmentX(Component.CENTER_ALIGNMENT); container.add(button); } public BoxWindow() { JPanel contentPane = (JPanel)getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); addAButton("Button 1", contentPane); addAButton("2", contentPane); addAButton("Button 3", contentPane); addAButton("Long-Named Button 4", contentPane); addAButton("Button 5", contentPane); … }

47 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers GridLayout: equal-sized grid of panels JPanel contentPane = (JPanel)getContentPane(); contentPane.setLayout(new GridLayout(0,2)); // grid layout with 2 columns; doesn’t specify number of rows! contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));

48 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers FlowLayout: flows in the rows JPanel contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));

49 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout managers GridBagLayout: more flexible grid CardLayout: changing components Very Hard, Complex!.. but Powerful!

50 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout TRAPS! Don't do this! Spacing components out – create space with rigid boxes – create space with “glue” (really bad name!) pane.add (Box.createRigidArea (new Dimension (0,5))); container.add (firstComponent); container.add (Box.createHorizontalGlue()); container.add (secondComponent);

51 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Layout TRAPS!... and there are more! Absolute positioning JPanel contentPane = getContentPane(); contentPane.setLayout(null); b1 = new JButton("one"); contentPane.add(b1); b2 = new JButton("two"); contentPane.add(b2); b3 = new JButton("three"); contentPane.add(b3); Insets insets = contentPane.getInsets(); b1.setBounds(25 + insets.left, 5 + insets.top, 75, 20); b2.setBounds(55 + insets.left, 35 + insets.top, 75, 20); b3.setBounds(150 + insets.left, 15 + insets.top, 75, 30);

52 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 “SwingApplication” example High-level view import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication { public JComponent createComponents() { … } public static void main (String[] args) { … } }

53 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 “SwingApplication” example main() public JComponent createComponents() { … } public static void main (String[] args) { … JFrame frame = new JFrame("SwingApplication"); SwingApplication app = new SwingApplication(); JComponent contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); … frame.pack(); frame.setVisible(true); }

54 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 “SwingApplication” example createComponents() public JComponent createComponents() { final JLabel label = new JLabel(labelPrefix + "0 "); JButton button = new JButton("I'm a Swing button!"); … > label.setLabelFor(button); JPanel pane = new JPanel(); pane.setBorder (BorderFactory.createEmptyBorder(30,30,10,30)); pane.setLayout(new GridLayout(0, 1)); pane.add(button); pane.add(label); return pane; } create border space!

55 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 “MyWindow” example Let’s design a window that looks like this when resized…

56 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Keeping things Flexible The “glue” example and “positioning” are nice to know, but watch out! Use your Layout Manager to do everything. Put panels within panels! Stack em', each panel can have its own layout. Flow Layout Border Grid

57 CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Recommendation Best Layout Manager: Border – Flexible: You know that the CENTER expands. – Easy: Not difficult to configure. – Sizes: Set Preferred Size Not as bad as Absolute Positioning, but not great! – Recommended – And hey, its the default for a reason!


Download ppt "1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 8: Layout Management."

Similar presentations


Ads by Google