Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java GUIs and Graphics CNS 3250. Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.

Similar presentations


Presentation on theme: "Java GUIs and Graphics CNS 3250. Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout."— Presentation transcript:

1 Java GUIs and Graphics CNS 3250

2 Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout managers  Drawing

3 GUIs and graphics in Java  Portable!  Listeners and events  Components  Layout managers  Portable!  Listeners and events  Components  Layout managers

4 A design consideration  Data components should exist independently from GUI components  They should have no knowledge of GUI  GUI components call upon data objects for information Why is this a good approach to use?  Data components should exist independently from GUI components  They should have no knowledge of GUI  GUI components call upon data objects for information Why is this a good approach to use?

5 History  AWT / Event Model (JDK 1.1)  Heavyweight components  Use OS “peers”  Event Dispatch Thread  Listeners to handle events  Swing (Java 2)  Lightweight components  Painted via graphics (not OS peers)  Preserves look and feel across platforms  AWT / Event Model (JDK 1.1)  Heavyweight components  Use OS “peers”  Event Dispatch Thread  Listeners to handle events  Swing (Java 2)  Lightweight components  Painted via graphics (not OS peers)  Preserves look and feel across platforms

6 Events How does your program know if the user clicks something with the mouse? Register a listener object. When the user clicks with the mouse, the system passes an event object to the listener. How does your program know if the user clicks something with the mouse? Register a listener object. When the user clicks with the mouse, the system passes an event object to the listener.

7 Listeners Implements one of the listener interfaces:  ActionListener  MouseListener  MouseMotionListener  WindowListener  etc. Listener interfaces are defined in java.awt.event Implements one of the listener interfaces:  ActionListener  MouseListener  MouseMotionListener  WindowListener  etc. Listener interfaces are defined in java.awt.event

8 ActionListener interface  Used with buttons, menu items, text fields  Only one method, actionPerformed  Takes an ActionEvent object as parameter  ActionEvent has a method that tells the command that triggered the name of the event.  For a button, the text of the button will be the command by default.  Used with buttons, menu items, text fields  Only one method, actionPerformed  Takes an ActionEvent object as parameter  ActionEvent has a method that tells the command that triggered the name of the event.  For a button, the text of the button will be the command by default.

9 Red Alert! import java.awt.event.*; import javax.swing.*; class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton; public RedAlert() { redAlertButton = new JButton("Red Alert"); add(redAlertButton); redAlertButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!"); } public static void main(String[] args) { RedAlert frame = new RedAlert(); frame.setSize(200, 100); frame.setVisible(true); }

10 Red Alert! import java.awt.event.*; import javax.swing.*; class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton; public RedAlert() { redAlertButton = new JButton("Red Alert"); add(redAlertButton); redAlertButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!"); } public static void main(String[] args) { RedAlert frame = new RedAlert(); frame.setSize(200, 100); frame.setVisible(true); }

11 MouseListener Includes several methods:  mouseClicked  mouseEntered  mouseExited  mousePressed  mouseReleased Includes several methods:  mouseClicked  mouseEntered  mouseExited  mousePressed  mouseReleased  Each method gets a MouseEvent object that tells the coordinates of the mouse and other info.  All methods have to be defined, whether you use them or not...

12 MouseAdapter  Defines all required methods for the MouseListener interface  Methods are empty.  Override the methods you actually want to use.  Use by making your class extend MouseAdapter.  Defines all required methods for the MouseListener interface  Methods are empty.  Override the methods you actually want to use.  Use by making your class extend MouseAdapter.

13 Adapters  All methods for the corresponding listener interface are defined.  Only useful if your class doesn't need to inherit from any other class.  Commonly used for mouse listeners, mouse motion listeners, window listeners.  There is no adapter for action listeners. Why not?  All methods for the corresponding listener interface are defined.  Only useful if your class doesn't need to inherit from any other class.  Commonly used for mouse listeners, mouse motion listeners, window listeners.  There is no adapter for action listeners. Why not?

14 Using listeners and events  Decide what kind of listener you need  This is usually based on the kind of input and the type of component you will be using  Define a class for that kind of listener Make a class that implements the interface Make a class that extends an adapter  Register the listener with the component  add____Listener, e.g. addActionListener  Decide what kind of listener you need  This is usually based on the kind of input and the type of component you will be using  Define a class for that kind of listener Make a class that implements the interface Make a class that extends an adapter  Register the listener with the component  add____Listener, e.g. addActionListener or

15 Red Alert! import java.awt.event.*; import javax.swing.*; class RedAlert extends JFrame implements ActionListener { private JButton redAlertButton; public RedAlert() { redAlertButton = new JButton("Red Alert"); add(redAlertButton); redAlertButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red Alert")) { System.out.println("Shields up!"); } public static void main(String[] args) { RedAlert frame = new RedAlert(); frame.setSize(200, 100); frame.setVisible(true); }

16 PolyDraw demo

17 Elf -- Java Ldraw display Uses OpenGL (JOGL)

18 POV-Ray -- Ray tracing

19 Components  Top-level containers  General-purpose containers  Displays  Controls  Text components  Top-level containers  General-purpose containers  Displays  Controls  Text components http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

20 Top-level containers  Every Java GUI program must have a top- level container.  Frame (AWT--java.awt)  JFrame (Swing--javax.swing)  Every Java GUI program must have a top- level container.  Frame (AWT--java.awt)  JFrame (Swing--javax.swing) http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

21 General-purpose containers  Panel (AWT)  JPanel (Swing)  Panel (AWT)  JPanel (Swing) http://java.sun.com/docs/books/tutorial/uiswing/components/components_pics.html

22 JPanel -- very commonly used Container for componentsDrawing

23 Displays JLabel  Can include an image in addition to (or instead of text)  Can use HTML formatting JLabel  Can include an image in addition to (or instead of text)  Can use HTML formatting

24 Controls  JButton  JComboBox  JList  JMenuItem  JButton  JComboBox  JList  JMenuItem What listeners and events?

25 Controls  JButton  JComboBox  JList  JMenuItem  JButton  JComboBox  JList  JMenuItem What listeners and events? ActionEvent PopupMenuEvent ActionEvent PopupMenuEvent ListSelectionEvent ActionEvent

26 Text components http://java.sun.com/docs/books/tutorial/uiswing/components/text.html

27 JTextArea  Used for multi-line text display and editing  Does not handle scrolling internally (as TextArea does)  Add to JScrollPane to get scrolling  Implements Scrollable interface  Can specify whether or not editing is allowed  Can specify line wrapping or not  Used for multi-line text display and editing  Does not handle scrolling internally (as TextArea does)  Add to JScrollPane to get scrolling  Implements Scrollable interface  Can specify whether or not editing is allowed  Can specify line wrapping or not

28 JEditorPane  Can display HTML  Not a "speed demon" according to our text book  Can get very complicated  Can display HTML  Not a "speed demon" according to our text book  Can get very complicated ' Castle A castle stands on a hill here. It doesn\'t appear to be inhabited, but it\'s hard to say for sure. '

29 PolyDraw components JScrollPane JPanel JButton JTextField JLabel JFrame JMenuBar JMenu JMenuItem JPanel JComboBox

30 Layout managers Where should components go? Usually: x, y coordinates. In Java location, size, and shape of components depends on another question: How big will the user's display be?  Could be anything from a huge, high-res display to a cell phone  Can change Where should components go? Usually: x, y coordinates. In Java location, size, and shape of components depends on another question: How big will the user's display be?  Could be anything from a huge, high-res display to a cell phone  Can change

31 Good news, bad news Good news  Adjusts components to fit size/shape of container  Can write Java GUIs with no special tools  Works well for different fonts, languages Bad news  Can be difficult to get what you want  Unexpected results Good news  Adjusts components to fit size/shape of container  Can write Java GUIs with no special tools  Works well for different fonts, languages Bad news  Can be difficult to get what you want  Unexpected results

32 Types of layout managers  BorderLayout  BoxLayout  CardLayout  FlowLayout  GridBagLayout  GridLayout  SpringLayout  BorderLayout  BoxLayout  CardLayout  FlowLayout  GridBagLayout  GridLayout  SpringLayout Pictures on the following slides are from the Java Tutorial: http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html

33 Using a layout manager  Create (or get access to) container  Set layout manager for container  Create component  Add component to container  Create (or get access to) container  Set layout manager for container  Create component  Add component to container Container cp = getContentPane(); cp.setLayout(new BorderLayout()); JButton button = new JButton("Button 1"); cp.add(button, BorderLayout.CENTER); These steps vary somewhat depending on the layout manager.

34 BorderLayout  Very commonly used  The center area grows/shrinks the most  Regions are (or used to be): Center, North, South, East, West  Very commonly used  The center area grows/shrinks the most  Regions are (or used to be): Center, North, South, East, West

35 BoxLayout  Relatively new  Fillers:  strut--1D fixed amount of space  rigid area--2D fixed amount of space  glue--variable amount of space, separates components as much as possible (Textbook says "spring" would be a better term than "glue".)  Relatively new  Fillers:  strut--1D fixed amount of space  rigid area--2D fixed amount of space  glue--variable amount of space, separates components as much as possible (Textbook says "spring" would be a better term than "glue".)

36 CardLayout  Used to switch back and forth between different layouts in the same space  Usually need to keep a reference to the layout manager object so that you can control which card is showing.  Used to switch back and forth between different layouts in the same space  Usually need to keep a reference to the layout manager object so that you can control which card is showing.

37 FlowLayout  The simplest layout manager  Can specify horizontal alignment  The simplest layout manager  Can specify horizontal alignment

38 GridBagLayout  Very flexible, but very complicated  See the p. 433 in Core Java Vol. I for a "Recipe for Making a Grid Bag Layout"  Note Step 7: "compile, run, and enjoy"  Must create GridBagConstraints objects  Book recommends a helper class GBC  NetBeans and other IDEs offer visual tools  Very flexible, but very complicated  See the p. 433 in Core Java Vol. I for a "Recipe for Making a Grid Bag Layout"  Note Step 7: "compile, run, and enjoy"  Must create GridBagConstraints objects  Book recommends a helper class GBC  NetBeans and other IDEs offer visual tools

39 GridLayout  Useful for a number of components that are the same size  Position is determined by order that components are added to the container  Useful for a number of components that are the same size  Position is determined by order that components are added to the container

40 SpringLayout  Meant to be as flexible as GridBagLayout but "more intuitive" It might be as flexible, but I think it's safe to say that it isn't more intuitive.  Meant to be as flexible as GridBagLayout but "more intuitive" It might be as flexible, but I think it's safe to say that it isn't more intuitive.

41 Drawing  Core Java (8th ed.) Vol. I, Ch. 7  Especially pages 296-322  Core Java (8th ed.) Vol. II, Ch. 7  Core Java (8th ed.) Vol. I, Ch. 7  Especially pages 296-322  Core Java (8th ed.) Vol. II, Ch. 7

42 Graphics class  Override paintComponent, which takes an object of class Graphics as a parameter  Call methods of Graphics class to draw shapes:  Override paintComponent, which takes an object of class Graphics as a parameter  Call methods of Graphics class to draw shapes: public void paintComponent (Graphics g) { g.setColor(Color.blue); g.fillOval(10, 20, 30, 30); } Upper left “corner” Width and height

43 import java.awt.*; import javax.swing.*; public class Draw extends JPanel { public void paintComponent(Graphics g) { g.setColor(Color.blue); g.fillOval(10, 20, 30, 30); } public static void main(String args[]) { JFrame frame = new JFrame(); Draw draw = new Draw(); frame.add(draw); frame.setSize(200, 150); frame.setVisible(true); } Graphics Jframe, JPanel

44 import java.awt.*; import javax.swing.*; public class Draw extends JPanel { public void paintComponent(Graphics g) { g.setColor(Color.blue); g.fillOval(10, 20, 30, 30); } public static void main(String args[]) { JFrame frame = new JFrame(); Draw draw = new Draw(); frame.add(draw); frame.setSize(200, 150); frame.setVisible(true); } paintComponent is not explicitly called.

45 paintComponent  Takes one parameter of type Graphics and has no return value  Must be ready to execute at any time  Don’t know when or how many times the JVM will call it.  Don’t call directly--call repaint method of component to tell the JVM to call paintComponent  Takes one parameter of type Graphics and has no return value  Must be ready to execute at any time  Don’t know when or how many times the JVM will call it.  Don’t call directly--call repaint method of component to tell the JVM to call paintComponent

46 JPanel  Opaque--must paint all pixels within its bounds  Call parent paintComponent to paint background:  Opaque--must paint all pixels within its bounds  Call parent paintComponent to paint background: public void paintComponent (Graphics g) { super.paintComponent(g); // drawing code goes here }

47 Drawing bitmaps  drawImage method of Graphics  Coordinates of upper left corner  Optionally height and width  Last parm is ImageObserver  drawImage method of Graphics  Coordinates of upper left corner  Optionally height and width  Last parm is ImageObserver Example on next slide.

48 public class Bitmap extends JPanel { Image img = null; public void paintComponent(Graphics g) { if (img != null) { g.drawImage(img, 10, 10, 180, 120, this); } public static void main(String args[]) { Bitmap draw = new Bitmap(); try { draw.img = ImageIO.read(new File("dunluce.jpg")); } catch (IOException x) { x.printStackTrace(); } draw.repaint(); } Some lines of code have been removed. Why check this? In javax.imageio Upper left “corner” Width and height ImageObserver

49 Graphics2D  More shapes  Control over stroke--lines more than one pixel wide  More fill options  Transformation--translate, rotate, scale  Clip shapes and select composition rules  Give rendering hints  More shapes  Control over stroke--lines more than one pixel wide  More fill options  Transformation--translate, rotate, scale  Clip shapes and select composition rules  Give rendering hints Core Java, p. 522 (8th ed.)

50 Using Java 2D Graphics API  Cast Graphics parameter to Graphics2D  Set stroke, paint, transformations, etc.  Create a shape  See shape hierarchy on page 526 (8th ed.)  Call draw or fill methods of Graphics2D object  Cast Graphics parameter to Graphics2D  Set stroke, paint, transformations, etc.  Create a shape  See shape hierarchy on page 526 (8th ed.)  Call draw or fill methods of Graphics2D object


Download ppt "Java GUIs and Graphics CNS 3250. Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout."

Similar presentations


Ads by Google