1 / 54

Chapter 12 GUI Basics

Chapter 12 GUI Basics. The Color Class.

bprice
Download Presentation

Chapter 12 GUI Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 12 GUI Basics

  2. The Color Class You can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each of which is represented by a byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model. Color c = new Color(r, g, b); r, g, and b specify a color by its red, green, and blue components. Example: Color c = new Color(228, 100, 255);

  3. Standard Colors Thirteen standard colors (black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color. The standard color names are constants, but they are named as variables with lowercase for the first word and uppercase for the first letters of subsequent words. Thus the color names violate the Java naming convention. Since JDK 1.4, you can also use the new constants: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW.

  4. Setting Colors You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c) Example: jbt.setBackground(Color.yellow); jbt.setForeground(Color.red);

  5. The Font Class Font Names • Standard font names that are supported in all platforms are: SansSerif, Serif, Monospaced, Dialog, or DialogInput. Font Style • Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2), and Font.BOLD + Font.ITALIC (3) Font myFont = new Font(name, style, size); Example: Font myFont = new Font("SansSerif ", Font.BOLD, 16); Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12); JButton jbtOK = new JButton("OK“); jbtOK.setFont(myFont);

  6. Finding All Available Font Names GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontnames = e.getAvailableFontFamilyNames(); for (int i = 0; i < fontnames.length; i++) System.out.println(fontnames[i]);

  7. Image Icons Java uses the javax.swing.ImageIcon class to represent an icon. An icon is a fixed-size picture; typically it is small and used to decorate components. Images are normally stored in image files. You can use new ImageIcon(filename) to construct an image icon. For example, the following statement creates an icon from an image file us.gif in the image directory under the current class path: ImageIcon icon = new ImageIcon("image/us.gif"); TestImageIcon Run

  8. Horizontal Alignments Horizontal alignment specifies how the icon and text are placed horizontally on a button. You can set the horizontal alignment using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. At present, LEADING and LEFT are the same and TRAILING and RIGHT are the same. Future implementation may distinguish them. The default horizontal alignment is SwingConstants.TRAILING.

  9. Vertical Alignments Vertical alignment specifies how the icon and text are placed vertically on a button. You can set the vertical alignment using one of the three constants: TOP, CENTER, BOTTOM. The default vertical alignment is SwingConstants.CENTER.

  10. Horizontal Text Positions Horizontal text position specifies the horizontal position of the text relative to the icon. You can set the horizontal text position using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. The default horizontal text position is SwingConstants.RIGHT.

  11. Vertical Text Positions Vertical text position specifies the vertical position of the text relative to the icon. You can set the vertical text position using one of the three constants: TOP, CENTER. The default vertical text position is SwingConstants.CENTER.

  12. JTextField A text field is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

  13. JTextField Constructors • JTextField(int columns) Creates an empty text field with the specified number of columns. • JTextField(String text) Creates a text field initialized with the specified text. • JTextField(String text, int columns) Creates a text field initialized with thespecified text and the column size.

  14. JTextField Properties • text • horizontalAlignment • editable • columns

  15. JTextField Methods • getText() Returns the string from the text field. • setText(String text) Puts the given string in the text field. • setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. • setColumns(int) Sets the number of columns in this text field.The length of the text field is changeable.

  16. JList A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.

  17. JList Constructors • JList() Creates an empty list. • JList(Object[] stringItems) Creates a new list initialized with items.

  18. JList Properties • selectedIndexd • selectedIndices • selectedValue • selectedValues • selectionMode • visibleRowCount

  19. Example: Using Lists This example gives a program that lets users select countries in a list and display the flags of the selected countries in the labels. ListDemo Run

  20. JScrollBar A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.

  21. Scroll Bar Properties

  22. Example: Using Scrollbars This example uses horizontal and vertical scrollbars to control a message displayed on a panel. The horizontal scrollbar is used to move the message to the left or the right, and the vertical scrollbar to move it up and down. ScrollBarDemo Run

  23. JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.

  24. Example: Using Sliders Rewrite the preceding program using the sliders to control a message displayed on a panel instead of using scroll bars. SliderDemo Run

  25. Chapter 13 Graphics

  26. Java Coordinate System

  27. Each GUI Component Has its Own Coordinate System

  28. The Graphics Class You can draw strings, lines, rectangles, ovals, arcs, polygons, and polylines, using the methods in the Graphics class.

  29. paintComponent Example In order to draw things on a component, you need to define a class that extends JPanel and overrides its paintComponent method to specify what to draw. The first program in this chapter can be rewritten using paintComponent. TestPaintComponent Run

  30. Drawing Geometric Figures • Drawing Strings • Drawing Lines • Drawing Rectangles • Drawing Ovals • Drawing Arcs • Drawing Polygons

  31. Drawing Strings drawLine(int x1, int y1, int x2, int y2); drawString(String s, int x, int y);

  32. Drawing Rectangles drawRect(int x, int y, int w, int h); fillRect(int x, int y, int w, int h);

  33. Drawing Rounded Rectangles drawRoundRect(int x, int y, int w, int h, int aw, int ah); fillRoundRect(int x, int y, int w, int h, int aw, int ah);

  34. Drawing Ovals drawOval(int x, int y, int w, int h); fillOval(int x, int y, int w, int h);

  35. Case Study: The FigurePanel Class This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel. FigurePanel

  36. Test FigurePanel This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel. TestFigurePanel Run

  37. Drawing Arcs drawArc(int x, int y, int w, int h, int angle1, int angle2); fillArc(int x, int y, int w, int h, int angle1, int angle2); Angles are in degree

  38. Drawing Arcs Example DrawArcs Run

  39. Drawing Polygons and Polylines int[] x = {40, 70, 60, 45, 20}; int[] y = {20, 40, 80, 45, 60}; g.drawPolygon(x, y, x.length); g.drawPolyline(x, y, x.length);

  40. Drawing Polygons Using the Polygon Class Polygon polygon = new Polygon(); polygon.addPoint(40, 59); polygon.addPoint(40, 100); polygon.addPoint(10, 100); g.drawPolygon(polygon);

  41. Drawing Polygons Example DrawPolygon Run

  42. Centering Display Using the FontMetrics Class You can display a string at any location in a panel. Can you display it centered? To do so, you need to use the FontMetrics class to measure the exact width and height of the string for a particular font. A FontMetrics can measure the following attributes: • public int getAscent() • public int getDescent() • public int getLeading() • public int getHeight() • public int stringWidth(String str) getLeading() getHeight() getAscent() getDescent()

  43. The FontMetrics Class FontMetrics is an abstract class. To get a FontMetrics object for a specific font, use the following getFontMetrics methods defined in the Graphics class: ·  public FontMetrics getFontMetrics(Font f) Returns the font metrics of the specified font. ·  public FontMetrics getFontMetrics() Returns the font metrics of the current font.

  44. TestCenterMessage Run

  45. Case Study: MessagePanel This case study develops a useful class that displays a message in a panel. The class enables the user to set the location of the message, center the message, and move the message with the specified interval. TestMessagePanel Run MessagePanel

  46. Case Study: StillClock StillClock DisplayClock Run

  47. Drawing Clock Since there are sixty seconds in one minute, the angle for the second hand is second  (2/60) xEnd = xCenter + handLength  sin() yEnd = yCenter - handLength  cos()

  48. Drawing Clock, cont. xEnd = xCenter + handLength  sin() yEnd = yCenter - handLength  cos() The position of the minute hand is determined by the minute and second. The exact minute value combined with seconds is minute + second/60. For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is (minute + second/60)  (2/60)

  49. Drawing Clock, cont. xEnd = xCenter + handLength  sin() yEnd = yCenter - handLength  cos() Since one circle is divided into twelve hours, the angle for the hour hand is (hour + minute/60 + second/(60  60)))  (2/12)

  50. Displaying Image Icons You learned how to create image icons and display image icons in labels and buttons. For example, the following statements create an image icon and display it in a label: ImageIcon icon = new ImageIcon("image/us.gif"); JLabel jlblImage = new JLabel(imageIcon); An image icon displays a fixed-size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows: Image image = imageIcon.getImage();

More Related