Presentation is loading. Please wait.

Presentation is loading. Please wait.

1CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. Introduction to JFC Swing.

Similar presentations


Presentation on theme: "1CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. Introduction to JFC Swing."— Presentation transcript:

1 1CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. Introduction to JFC Swing

2 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.2 Java and user interfaces n Platform independence for user interfaces has been notoriously hard n Java’s first foray: AWT (Abstract Window Toolkit) –provided common code for widgets — components such as windows, buttons, menus, … –good first start, but platform independence wasn’t quite there AWT relied on windowing code on native machine –so in practice, somewhat flaky

3 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.3 Java and user interfaces (2) n Current Java 2: integrated JFC & Swing n Swing –GUI component toolkit, including all widgets –no native windowing code, to improve on AWT n JFC (Java Foundation Classes) –includes Swing components –includes other software such as… “pluggable look and feel” accessibility support for disabled n AWT still there, but we can mostly ignore it

4 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.4 Building a Swing GUI n Consider the following “SwingApplication” (courtesy of Sun’s Java Swing Tutorial) n Every app defines a hierarchy of components –“component” = “widget”

5 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.5 Model-View-Controller Architecture n What defines a component? n In Swing (and similar frameworks), a component has three crucial elements: –Model: what data is associated with component –View: how the component is displayed on-screen –Controller: how the component responds to user interaction / events n Example: the scrollbar Model min = 0 max = 255 value = 87 ViewController mouse click on end mouse click on bar mouse drag on scroller

6 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.6 Pluggable Look and Feel Each picture shows the same program but with a different look and feel

7 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.7 Swing components n Top-level containers JFrameJDialogJApplet

8 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.8 Swing components n General-purpose containers JSplitPane JToolbar JScrollPane JPanel JTabbedPane

9 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.9 Swing components n Special-purpose containers JLayeredPane JInternalFrame

10 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.10 Swing components n Basic Controls JButton JComboBox JList JMenu JSlider JTextField

11 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.11 Swing components n Uneditable displays JLabel JProgressBar JToolTip

12 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.12 Swing components n Editable displays JColorChooserJFileChooser JTreeJTextJTable

13 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.13 Creating components n Just call the constructors! n All we’ve done is create the data structures n Still need to: –add components to container –lay out container frame = new JFrame (...); button = new JButton (...); label = new JLabel (...); pane = new JPanel (); …

14 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.14 Adding components n Add components to top-level container... typically, to content pane n Add components to intermediate containers frame.getContentPane().add (button); JPanel panel = new Jpanel (); panel.add (button); // … and more… frame.getContentPane().add (panel);

15 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.15 Example import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } pack() causes a window to be sized to fit the preferred size and layouts of its sub-components

16 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.16 Laying out components n We could just specify absolute positioning — i.e., exact window coordinates n Why is this not (typically) a good idea?

17 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.17 courtesy of java.sun.com’s Layout Management short course Laying out components n Problems with absolute positioning –window expanded, components stay put 7 3

18 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.18 Laying out components n Problems with absolute positioning (cont.) –components designed for a specific look-and-feel or font size –components designed for a specific language Auf Wiedersehen (note: Wieder = “again”!)

19 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.19 public Dimension getPreferredSize();// desired size public Dimension getMinimumSize();// smallest desired size public Dimension getMaximumSize();// largest desired size Laying out components n Solution: Layout managers! –layout manager = algorithm for positioning and sizing of GUI components n Swing’s LayoutManager interface –each Component has: –managers use this info to compute layouts –caveat: “Layout managers can respect or ignore as much or as little of this information as they see fit” (!)

20 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.20 Layout managers n BorderLayout (the default) JPanel pane = new JPanel(); pane.setLayout (new BorderLayout()); // not really needed … pane.add (buttonNorth, BorderLayout.NORTH); pane.add (buttonCenter, BorderLayout.CENTER); …

21 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.21 Layout managers n 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!

22 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.22 Layout managers n BoxLayout: across or up/down private void addAButton(String text, Container container) { JButton button = new JButton(text); button.setAlignmentX(Component.CENTER_ALIGNMENT); container.add(button); } public BoxWindow() { Container contentPane = 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); … }

23 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.23 Layout managers n GridLayout: equal-sized grid of panels Container contentPane = 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"));

24 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.24 Layout managers n FlowLayout: flows the rows, you knows Container 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"));

25 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.25 Layout extras n 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);

26 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.26 Layout extras n Absolute positioning Container 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);

27 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.27 Borders n Every JComponent can have one or more borders. n The class BorderFactory may be used to create standard borders pane.setBorder(BorderFactory. createLineBorder(Color.black)); n Using a compound border, you can combine any two borders, which can themselves be compound borders BorderFactory.createCompoundBorder(border1, border2);

28 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.28 Simple Borders 1.Simple Borders 2.Titled Borders 3. Compound Borders 1 23

29 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.29 Example: SwingApplication n High-level view import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication { public Component createComponents() { … } public static void main (String[] args) { … } }

30 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.30 Example: SwingApplication n main() public Component createComponents() { … } public static void main (String[] args) { … JFrame frame = new JFrame("SwingApplication"); SwingApplication app = new SwingApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); … frame.pack(); frame.setVisible(true); }

31 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.31 Example: SwingApplication n createComponents() public Component 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!

32 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.32 Class exercise: MyLayout n How would we use the layout managers to produce the following layout?

33 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.33 Example: MyLayout2 n How about this layout?

34 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.34 Example: MyLayout2 WestCenterEast 123 456 783 North Center Up Gowiththe flow South Down Nina Pinta Santa Maria (vertical glue) BorderLayout () GridLayout (0,3,10,10)BorderLayout () FlowLayout () BoxLayout (Y_AXIS) n One possible structure...

35 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.35 Handling GUI events n Ok, you’ve laid out the perfect window. n Now the user does something — an event occurs. n How do you handle the event? n Wait, what events are we talking about? User clicks a button, presses Return while typing in a text field, or chooses a menu item User closes a frame (main window) User presses a mouse button while the cursor is over a component User moves the mouse over a component Component becomes visible Component gets the keyboard focus Table or list selection changes

36 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.36 Programming the GUI n Sequential/procedural programming –your program is (almost) always in control –for user input, the program dictates when/how, and the user responds yourFoo() yourSubFoo() systemFoo() yourSubFoo() yourFoo() > ls */*.java_

37 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.37 Programming the GUI n Sequential/procedural programming (cont.) –the good points easy to think about: one event, then the next, … easy to design and represent with well-known models easy to program with today’s programming languages –the big bad point program dictates when/how user must respond Great for the programmer… What about the user?!?!?

38 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.38 Programming the GUI n Event-driven programming –system / toolkit handles much of processing –events on a queue, handled in turn –advantages flexible interaction — user decides when/how easier coding — you code only the “important” stuff better for the programmer and the user! MAIN LOOP yourClickHandler() yourScrollHandler() yourKeyHandler()...

39 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.39 Ways to handle events n “Macintosh-style” event handling –decide what the event is –figure out what window it goes to –handle the event void handleEvent (event) { switch (event->type) { case MOUSE_CLICK: window = event->window; > case …: } NB: Pseudocode!

40 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.40 Ways to handle events n Callback model –create widget, register callback function –callback function called for each event void myButtonClickCallback (window, other_data) { … } void main () { button = new Button (label, …); registerCallback (button, CLICK_CALLBACK, &(myButtonClickCallback)); } NB: Pseudocode!

41 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.41 Ways to handle events n Object-oriented event handling –the way Java does it! –based on the OOP component hierarchy define event-handling methods for components components can (of course) inherit these methods from parent components –also based on the Model-View-Control Architecture (remember?) –now let’s look at this in detail…

42 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.42 Swing sources and listeners n Event sources generate events n Event listeners respond to them User clicks a button, presses Return whileActionListener typing in a text field, or chooses a menu item User closes a frame (main window)WindowListener User presses a mouse button while the cursorMouseListener is over a component User moves the mouse over a componentMouseMotionListener

43 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.43 ActionEvent n A class with three methods: n We won’t use these methods at the moment, but the keep the class in mind! String getActionCommand (); int getModifiers (); String paramString ();

44 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.44 ActionListener n An interface with a single method: n We implement the interface as follows: n Review: How is an interface different from a class? public interface ActionListener { void actionPerformed (ActionEvent e); } public class MyClassThatListens … implements ActionListener { … public void actionPerformed (ActionEvent e) { … } … }

45 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.45 The 3-step program to handling events n 1. Code that implements the listener class n 2. Code that implements the listener methods n 3. Code that registers the listener to a source public class MyClass implements ActionListener { … } component.addActionListener (instanceOfMyClass); public void actionPerformed (ActionEvent e) { … }

46 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.46 Example: ButtonTest n Beep when the user clicks the button import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonTest { public static class MyActionListener implements ActionListener { public void actionPerformed (ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } } public static void main (String[] args) { JFrame frame = new JFrame ("Program"); JButton button = new JButton ("Click Me"); button.addActionListener (new MyActionListener());... } step 1 step 2 step 3

47 Graphics JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. TM Copyright © 2002-2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Classroom teachers and workshop instructors may reproduce these slides for face-to-face teaching purposes.

48 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.48 Objectives: n Learn about paint and repaint methods n Learn about coordinates and colors n Review shape drawing methods n Learn to use fonts and draw graphics text Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

49 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.49 Graphics in Java n Java libraries offer two graphics packages: Graphics and Graphics2D. n Graphics is really not a package but a class in the java.awt package, which provides only most basic capabilities. n Graphics2D and related classes in java.awt support better graphics with color gradients, line styles, etc. n Here we only deal with Graphics. Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

50 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.50 Graphics in Windows n In a windowing environment, a picture must be be repainted every time we move, reopen or reshape the window. n The program must have one “central” place or method where all the drawing happens. n The operating system sends a “message” to the program to repaint its window when necessary. Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

51 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.51 paint and paintComponent n The javax.swing.JFrame class (which represents application windows) has one method, called paint, where all the drawing takes place. n In Swing, paint calls paintComponent for each of the GUI components in the window. n A programmer creates pictures by overriding the default paintComponent methods (or the paint method). Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

52 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.52 paint and paintComponent (cont’d) n paint takes one argument of the type Graphics: import java.awt.*; import javax.swing.*; public class MyWindow extends JFrame {... public void paint(Graphics g) { super.paint(g);... } Defines the graphics “context” (location, size, coordinates, etc.) Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

53 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.53 paint and paintComponent (cont’d) n The same for paintComponent: import java.awt.*; import javax.swing.*; public class MyCanvas extends JPanel {... public void paintComponent(Graphics g) { super.paintComponent(g);... } Or another Swing GUI component Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

54 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.54 paint and paintComponent (cont’d) n A programmer never calls paint or paintComponent directly. repaint is called instead whenever you need to refresh the picture (e.g. after adding, moving, or changing some elements): MyCanvas canvas = new MyCanvas();... balloon.move(dx, dy); repaint();... repaint takes no arguments: the graphics context is restored and sent to paintComponent automatically Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

55 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.55 Coordinates x y Origin: the upper- left corner of the component y -axis points down, as in many other graphics packages Units: pixels Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

56 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.56 Coordinates (cont’d) n A GUI component provides getWidth and getHeight methods that return its respective dimensions. n They can be used to produce scalable graphics. n getWidth, getHeight only work after the component has been placed (e.g., don’t call them from a component’s constructor). Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

57 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.57 Coordinates (cont’d) n The position of a rectangle, oval, and even an arc is defined by using its “bounding rectangle,” described by x, y, width, height: x, y Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

58 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.58 Colors n The color attribute is set by calling g.setColor and stays in effect until changed again: n You can form a color with any RGB values: g.setColor(Color.blue); g.draw... g.setColor(Color.lightGray);... int rVal = 5, gVal = 255, bVal = 40; Color yourEyes = new Color (rVal, gVal, bVal); Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

59 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.59 Colors (cont’d) n javax.swing.JColorChooser let’s you choose a color in a GUI application: Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

60 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.60 Drawing Basic Shapes g.drawLine (x1, y1, x2, y2); g.clearRect (x, y, w, h); g.drawRect (x, y, w, h); g.fillRect (x, y, w, h); g.drawRoundRect (x, y, w, h, horzD, vertD); g.fillRoundRect (x, y, w, h, horzD, vertD); g.drawOval (x, y, w, h); g.fillOval (x, y, w, h); g.drawArc (x, y, w, h, fromDegr, measureDegrs); Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

61 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.61 x, y Basic Shapes (cont’d) g.drawPolygon (xCoords, yCoords, nPoints); g.fillPolygon (xCoords, yCoords, nPoints); g.drawPolyline (xCoords, yCoords, nPoints); g.drawString (str, x, y); g.drawImage (img, x, y, this); abc ImageObserver, usually this Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

62 CS 680: Developing User Interfaces. Dario Salvucci, Drexel University.62 Fonts Font font = new Font (name, style, size); g.setFont (font); abc "Serif" abc "SansSerif" abc "Monospaced" Font.PLAIN Font.BOLD Font.ITALIC int (pixels) Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.


Download ppt "1CS 680: Developing User Interfaces. Dario Salvucci, Drexel University. Introduction to JFC Swing."

Similar presentations


Ads by Google