archive-edu.com » EDU » H » HWS.EDU

Total: 727

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Javanotes 7.0, Section 4.6 -- More on Program Design
    colored rectangles Each rectangle is w pixels wide and h pixels high The number of rows is given by the first parameter and the number of columns by the second Initially all rectangles are black Note The rows are numbered from 0 to rows 1 and the columns are numbered from 0 to cols 1 public static void open int rows int cols int w int h Sets the color of one of the rectangles in the window Precondition row and col are in the valid range of row and column numbers and r g and b are in the range 0 to 255 inclusive Postcondition The color of the rectangle in row number row and column number col has been set to the color specified by r g and b r gives the amount of red in the color with 0 representing no red and 255 representing the maximum possible amount of red The larger the value of r the more red in the color g and b work similarly for the green and blue color components public static void setColor int row int col int r int g int b Gets the red component of the color of one of the rectangles Precondition row and col are in the valid range of row and column numbers Postcondition The red component of the color of the specified rectangle is returned as an integer in the range 0 to 255 inclusive public static int getRed int row int col Like getRed but returns the green component of the color public static int getGreen int row int col Like getRed but returns the blue component of the color public static int getBlue int row int col Tests whether the mosaic window is currently open Precondition None Postcondition The return value is true if the window is open when this function is called and it is false if the window is closed public static boolean isOpen Inserts a delay in the program to regulate the speed at which the colors are changed for example Precondition milliseconds is a positive integer Postcondition The program has paused for at least the specified number of milliseconds where one second is equal to 1000 milliseconds public static void delay int milliseconds Remember that these subroutines are members of the Mosaic class so when they are called from outside Mosaic the name of the class must be included as part of the name of the routine For example we ll have to use the name Mosaic isOpen rather than simply isOpen You ll notice that the comments on the subroutine don t specify what happens when the preconditions are not met Although a subroutine is not really obligated by its contract to do anything particular in that case it would be good to know what happens For example if the precondition row and col are in the valid range of row and column numbers on the setColor or getRed routine is violated an IllegalArgumentException will be thrown Knowing that fact would allow you to write programs that catch and handle the exception and it would be good to document it with a throws doc tag in the Javadoc comment Other questions remain about the behavior of the subroutines For example what happens if you call Mosaic open and there is already a mosaic window open on the screen In fact the old one will be closed and a new one will be created It s difficult to fully document the behavior of a piece of software sometimes you just have to experiment or look at the full source code My idea for a program is to use the Mosaic class as the basis for a neat animation I want to fill the window with randomly colored squares and then randomly change the colors in a loop that continues as long as the window is open Randomly change the colors could mean a lot of different things but after thinking for a while I decide it would be interesting to have a disturbance that wanders randomly around the window changing the color of each square that it encounters Here s a picture showing what the contents of the window might look like at one point in time With basic routines for manipulating the window as a foundation I can turn to the specific problem at hand A basic outline for my program is Open a Mosaic window Fill window with random colors Move around changing squares at random Filling the window with random colors seems like a nice coherent task that I can work on separately so let s decide to write a separate subroutine to do it The third step can be expanded a bit more into the steps Start in the middle of the window then keep moving to new squares and changing the color of those squares This should continue as long as the mosaic window is still open Thus we can refine the algorithm to Open a Mosaic window Fill window with random colors Set the current position to the middle square in the window As long as the mosaic window is open Randomly change color of the square at the current position Move current position up down left or right at random I need to represent the current position in some way That can be done with two int variables named currentRow and currentColumn that hold the row number and the column number of the square where the disturbance is currently located I ll use 16 rows and 20 columns of squares in my mosaic so setting the current position to be in the center means setting currentRow to 8 and currentColumn to 10 I already have a subroutine Mosaic open to open the window and I have a function Mosaic isOpen to test whether the window is open To keep the main routine simple I decide that I will write two more subroutines of my own to carry out the two tasks

    Original URL path: http://math.hws.edu/javanotes/c4/s6.html (2016-02-07)
    Open archived version from archive


  • Javanotes 7.0, Section 4.7 -- The Truth About Declarations
    in the program A recommended style rule for named constants is to give them names that consist entirely of upper case letters with underscore characters to separate words if necessary For example the preferred style for the interest rate constant would be public final static double INTEREST RATE 0 05 This is the style that is generally used in Java s standard classes which define many named constants For example we have already seen that the Math class contains a variable Math PI This variable is declared in the Math class as a public final static variable of type double Similarly the Color class contains named constants such as Color RED and Color YELLOW which are public final static variables of type Color Many named constants are created just to give meaningful names to be used as parameters in subroutine calls For example the standard class named Font contains named constants Font PLAIN Font BOLD and Font ITALIC These constants are used for specifying different styles of text when calling various subroutines in the Font class Enumerated type constants see Subsection 2 3 3 are also examples of named constants The enumerated type definition enum Alignment LEFT RIGHT CENTER defines the constants Alignment LEFT Alignment RIGHT and Alignment CENTER Technically Alignment is a class and the three constants are public final static members of that class Defining the enumerated type is similar to defining three constants of type say int public static final int ALIGNMENT LEFT 0 public static final int ALIGNMNENT RIGHT 1 public static final int ALIGNMENT CENTER 2 In fact this is how things were generally done before the introduction of enumerated types and it is what is done with the constants Font PLAIN Font BOLD and Font ITALIC mentioned above Using the integer constants you could define a variable of type int and assign it the values ALIGNMENT LEFT ALIGNMENT RIGHT or ALIGNMENT CENTER to represent different types of alignment The only problem with this is that the computer has no way of knowing that you intend the value of the variable to represent an alignment and it will not raise any objection if the value that is assigned to the variable is not one of the three valid alignment values With the enumerated type on the other hand the only values that can be assigned to a variable of type Alignment are the constant values that are listed in the definition of the enumerated type Any attempt to assign an invalid value to the variable is a syntax error which the computer will detect when the program is compiled This extra safety is one of the major advantages of enumerated types Curiously enough one of the major reasons to use named constants is that it s easy to change the value of a named constant Of course the value can t change while the program is running But between runs of the program it s easy to change the value in the source code and recompile the program Consider the interest rate example It s quite possible that the value of the interest rate is used many times throughout the program Suppose that the bank changes the interest rate and the program has to be modified If the literal number 0 05 were used throughout the program the programmer would have to track down each place where the interest rate is used in the program and change the rate to the new value This is made even harder by the fact that the number 0 05 might occur in the program with other meanings besides the interest rate as well as by the fact that someone might have say used 0 025 to represent half the interest rate On the other hand if the named constant INTEREST RATE is declared and used consistently throughout the program then only the single line where the constant is initialized needs to be changed As an extended example I will give a new version of the RandomMosaicWalk program from the previous section This version uses named constants to represent the number of rows in the mosaic the number of columns and the size of each little square The three constants are declared as final static member variables with the lines final static int ROWS 20 Number of rows in mosaic final static int COLUMNS 30 Number of columns in mosaic final static int SQUARE SIZE 15 Size of each square in mosaic The rest of the program is carefully modified to use the named constants For example in the new version of the program the Mosaic window is opened with the statement Mosaic open ROWS COLUMNS SQUARE SIZE SQUARE SIZE Sometimes it s not easy to find all the places where a named constant needs to be used If you don t use the named constant consistently you ve more or less defeated the purpose It s always a good idea to run a program using several different values for any named constant to test that it works properly in all cases Here is the complete new program RandomMosaicWalk2 with all modifications from the previous version shown in red I ve left out some of the comments to save space public class RandomMosaicWalk2 final static int ROWS 20 Number of rows in mosaic final static int COLUMNS 30 Number of columns in mosaic final static int SQUARE SIZE 15 Size of each square in mosaic static int currentRow Row currently containing the disturbance static int currentColumn Column currently containing the disturbance public static void main String args Mosaic open ROWS COLUMNS SQUARE SIZE SQUARE SIZE fillWithRandomColors currentRow ROWS 2 start at center of window currentColumn COLUMNS 2 while Mosaic isOpen changeToRandomColor currentRow currentColumn randomMove Mosaic delay 1 end main static void fillWithRandomColors for int row 0 row ROWS row for int column 0 column COLUMNS column changeToRandomColor row column end fillWithRandomColors static void changeToRandomColor int rowNum int colNum int red int 256 Math random Choose random levels in range

    Original URL path: http://math.hws.edu/javanotes/c4/s7.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 5.3 -- Programming with Objects
    already seen that one of the major features of object oriented programming is the ability to create subclasses of a class The subclass inherits all the properties or behaviors of the class but can modify and add to what it inherits In Section 5 5 you ll learn how to create subclasses What you don t know yet is that every class in Java with just one exception is a subclass of some other class If you create a class and don t explicitly make it a subclass of some other class then it automatically becomes a subclass of the special class named Object Object is the one class that is not a subclass of any other class Class Object defines several instance methods that are inherited by every other class These methods can be used with any object whatsoever I will mention just one of them here You will encounter more of them later in the book The instance method toString in class Object returns a value of type String that is supposed to be a string representation of the object You ve already used this method implicitly any time you ve printed out an object or concatenated an object onto a string When you use an object in a context that requires a string the object is automatically converted to type String by calling its toString method The version of toString that is defined in Object just returns the name of the class that the object belongs to concatenated with a code number called the hash code of the object this is not very useful When you create a class you can write a new toString method for it which will replace the inherited version For example we might add the following method to any of the PairOfDice classes from the previous section Return a String representation of a pair of dice where die1 and die2 are instance variables containing the numbers that are showing on the two dice public String toString if die1 die2 return double die1 else return die1 and die2 If dice refers to a PairOfDice object then dice toString will return strings such as 3 and 6 5 and 1 and double 2 depending on the numbers showing on the dice This method would be used automatically to convert dice to type String in a statement such as System out println The dice came up dice so this statement might output The dice came up 5 and 1 or The dice came up double 2 You ll see another example of a toString method in the next section 5 3 3 Writing and Using a Class As an example we will write an animation program based on the same animation framework that was used in Subsection 3 9 3 The animation shows a number of semi transparent disk that grow in size as the animation plays The disks have random colors and locations When a disk gets too big or sometimes just at random the disk disappears and is replaced with a new disk at a random location Here is a screenshot from the program A disk in this program can be represented as an object A disk has properties color location and size that can be instance variables in the object As for instance methods we need to think about what we might want to do with a disk An obvious candidate is that we need to be able to draw it so we can include an instance method draw g where g is a graphics context that will be used to do the drawing The class can also include one or more constructors A constructor initializes the object It s not always clear what data should be provided as parameters to the constructors In this case as an example the constructor s parameters specify the location and size for the circle but the constructor makes up a color using random values for the red green and blue components Here s the complete class import java awt Color import some standard GUI classes import java awt Graphics A simple class that holds the size color and location of a colored disk with a method for drawing the filled circle in a graphics context The circle is drawn as a filled oval with a black outline public class CircleInfo public int radius The radius of the circle public int x y The location of the center of the circle public Color color The color of the circle Create a CircleInfo with a given location and radius and with a randomly selected semi transparent color param centerX The x coordinate of the center param centerY The y coordinate of the center param rad The radius of the circle public CircleInfo int centerX int centerY int rad x centerX y centerY radius rad int red int 255 Math random int green int 255 Math random int blue int 255 Math random color new Color red green blue 100 Draw the disk in graphics context g with a black outline public void draw Graphics g g setColor color g fillOval x radius y radius 2 radius 2 radius g setColor Color BLACK g drawOval x radius y radius 2 radius 2 radius It would probably be better style to write getters and setters for the instance variables but to keep things simple I made them public The main program for my animation is a class GrowingCircleAnimation The program uses 100 disks each one represented by an object of type CircleInfo To make that manageable the program uses an array of objects The array variable is a member variable in the class private CircleInfo circleData holds the data for all 100 circles Note that it is not static GUI programming generally uses objects rather than static variables and methods Basically this is because we can imagine having several GrowingCircleAnimations going on at the same time each with its own array of disks Each animation would be represented by

    Original URL path: http://math.hws.edu/javanotes/c5/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 6.1 -- The Basic GUI Application
    of type JFrame and sets it to refer to a new window object with the statement JFrame window new JFrame GUI Test The parameter the string GUI test in the constructor specifies the title that will be displayed in the titlebar of the window This line creates the window object but the window itself is not yet visible on the screen Before making the window visible some of its properties are set with these statements window setContentPane content window setSize 250 100 window setLocation 100 100 The first line here sets the content of the window The content itself was created earlier in the main program The second line says that the window will be 250 pixels wide and 100 pixels high The third line says that the upper left corner of the window will be 100 pixels over from the left edge of the screen and 100 pixels down from the top Once all this has been set up the window is actually made visible on the screen with the command window setVisible true It might look as if the program ends at that point and in fact the main routine does end However the window is still on the screen and the program as a whole does not end until the user clicks the OK button Once the window was opened a new thread was created to manage the graphical user interface and that thread continues to run even after main has finished The content that is displayed in a JFrame is called its content pane In addition to its content pane a JFrame can also have a menu bar which is a separate thing that I will talk about later A basic JFrame already has a blank content pane you can either add things to that pane or you can replace the basic content pane entirely In my sample program the line window setContentPane content replaces the original blank content pane with a different component Remember that a component is just a visual element of a graphical user interface In this case the new content is a component of type JPanel JPanel is another of the fundamental classes in Swing The basic JPanel is again just a blank rectangle There are two ways to make a useful JPanel The first is to add other components to the panel the second is to draw something in the panel Both of these techniques are illustrated in the sample program In fact you will find two JPanels in the program content which is used to contain other components and displayPanel which is used as a drawing surface Let s look more closely at displayPanel This variable is of type HelloWorldDisplay which is a static nested class inside the HelloWorldGUI2 class Nested classes were introduced in Section 5 8 This class defines just one instance method paintComponent which overrides a method of the same name in the JPanel class private static class HelloWorldDisplay extends JPanel public void paintComponent Graphics g super paintComponent g g drawString Hello World 20 30 The paintComponent method is called by the system when a component needs to be painted on the screen In the JPanel class the paintComponent method simply fills the panel with the panel s background color The paintComponent method in HelloWorldDisplay begins by calling super paintComponent g This calls the version of paintComponent that is defined in the superclass JPanel that is it fills the panel with the background color See Subsection 5 6 2 for a discussion of the special variable super Then it calls g drawString to paint the string Hello World onto the panel The net result is that whenever a HelloWorldDisplay is shown on the screen it displays the string Hello World We will often use JPanels in this way as drawing surfaces Usually when we do this we will define a class that is a subclass of JPanel and we will write a paintComponent method in that class to draw the desired content in the panel The subclass of JPanel can be defined either as a separate class in its own file or as a nested class In simple cases I will tend to use a nested class for the convenience 6 1 2 Components and Layout Another way of using a JPanel is as a container to hold other components Java has many classes that define GUI components Except for top level components like windows components must be added to a container before they can appear on the screen In the sample program the variable named content refers to a JPanel that is used as a container Two other components are added to that container This is done in the statements content add displayPanel BorderLayout CENTER content add okButton BorderLayout SOUTH Here content refers to an object of type JPanel later in the program this panel becomes the content pane of the window The first component that is added to content is displayPanel which as discussed above displays the message Hello World The second is okButton which represents the button that the user clicks to close the window The variable okButton is of type JButton the Java class that represents push buttons The BorderLayout stuff in these statements has to do with how the two components are arranged in the container When components are added to a container there has to be some way of deciding how those components are arranged inside the container This is called laying out the components in the container and the most common technique for laying out components is to use a layout manager A layout manager is an object that implements some policy for how to arrange the components in a container different types of layout manager implement different policies One type of layout manager is defined by the BorderLayout class In the program the statement content setLayout new BorderLayout creates a new BorderLayout object and tells the content panel to use the new object as its layout manager Essentially this

    Original URL path: http://math.hws.edu/javanotes/c6/s1.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 6.2 -- Graphics and Painting
    get things right if all drawing is done in one method Second even if you could directly draw the modifications you would still have to save enough information about the modifications to enable paintComponent to redraw the component correctly on demand You will see how all this works in practice as we work through examples in the rest of this chapter For now we will spend the rest of this section looking at how to get some actual drawing done 6 2 1 Coordinates The screen of a computer is a grid of little squares called pixels The color of each pixel can be set individually and drawing on the screen just means setting the colors of individual pixels A graphics context draws in a rectangle made up of pixels A position in the rectangle is specified by a pair of integer coordinates x y The upper left corner has coordinates 0 0 The x coordinate increases from left to right and the y coordinate increases from top to bottom The illustration shows a 20 pixel by 12 pixel component with very large pixels A small line rectangle and oval are shown as they would be drawn by coloring individual pixels Note that properly speaking the coordinates don t belong to the pixels but to the grid lines between them For any component you can find out the size of the rectangle that it occupies by calling the instance methods getWidth and getHeight which return the number of pixels in the horizontal and vertical directions respectively In general it s not a good idea to assume that you know the size of a component since the size is often set by a layout manager and can even change if the component is in a window and that window is resized by the user This means that it s good form to check the size of a component before doing any drawing on that component For example you can use a paintComponent method that looks like public void paintComponent Graphics g super paintComponent g int width getWidth Find out the width of this component int height getHeight Find out its height Draw the content of the component Of course your drawing commands will have to take the size into account That is they will have to use x y coordinates that are calculated based on the actual height and width of the component However if you are sure that you know the size using constants for the width and height can make the drawing easier 6 2 2 Colors You will probably want to use some color when you draw Java is designed to work with the RGB color system An RGB color is specified by three numbers that give the level of red green and blue respectively in the color A color in Java is an object of the class java awt Color You can construct a new color by specifying its red blue and green components For example Color myColor new Color r g b There are two constructors that you can call in this way In the one that I almost always use r g and b are integers in the range 0 to 255 In the other they are numbers of type float in the range 0 0F to 1 0F Recall that a literal of type float is written with an F to distinguish it from a double number Often you can avoid constructing new colors altogether since the Color class defines several named constants representing common colors Color WHITE Color BLACK Color RED Color GREEN Color BLUE Color CYAN Color MAGENTA Color YELLOW Color PINK Color ORANGE Color LIGHT GRAY Color GRAY and Color DARK GRAY There are older alternative names for these constants that use lower case rather than upper case constants such as Color red instead of Color RED but the upper case versions are preferred because they follow the convention that constant names should be upper case An alternative to RGB is the HSB color system In the HSB system a color is specified by three numbers called the hue the saturation and the brightness The hue is the basic color ranging from red through orange through all the other colors of the rainbow The brightness is pretty much what it sounds like A fully saturated color is a pure color tone Decreasing the saturation is like mixing white or gray paint into the pure color In Java the hue saturation and brightness are always specified by values of type float in the range from 0 0F to 1 0F The Color class has a static member function named getHSBColor for creating HSB colors To create the color with HSB values given by h s and b you can say Color myColor Color getHSBColor h s b For example to make a color with a random hue that is as bright and as saturated as possible you could use Color randomColor Color getHSBColor float Math random 1 0F 1 0F The type cast is necessary because the value returned by Math random is of type double and Color getHSBColor requires values of type float By the way you might ask why RGB colors are created using a constructor while HSB colors are created using a static member function The problem is that we would need two different constructors both of them with three parameters of type float Unfortunately this is impossible You can have two constructors only if the number of parameters or the parameter types differ The RGB system and the HSB system are just different ways of describing the same set of colors It is possible to translate between one system and the other The best way to understand the color systems is to experiment with them The sample program SimpleColorChooser java lets you do that You won t understand the source code at this time but you can run it to play with color selection or to find the RGB or HSB values for the color that want One of the properties of a Graphics object is the current drawing color which is used for all drawing of shapes and text If g is a graphics context you can change the current drawing color for g using the method g setColor c where c is a Color For example if you want to draw in green you would just say g setColor Color GREEN before doing the drawing The graphics context continues to use the color until you explicitly change it with another setColor command If you want to know what the current drawing color is you can call the function g getColor which returns an object of type Color This can be useful if you want to change to another drawing color temporarily and then restore the previous drawing color Every component has an associated foreground color and background color Generally the component is filled with the background color before anything else is drawn although some components are transparent meaning that the background color is ignored When a new graphics context is created for a component the current drawing color is set to the foreground color Note that the foreground color and background color are properties of the component not of a graphics context The foreground and background colors of a component can be set by calling instance methods component setForeground color and component setBackground color which are defined in the Component class and therefore are available for use with any component This can be useful even for standard components if you want them to use colors that are different from the defaults 6 2 3 Fonts A font represents a particular size and style of text The same character will appear different in different fonts In Java a font is characterized by a font name a style and a size The available font names are system dependent but you can always use the following four strings as font names Serif SansSerif Monospaced and Dialog A serif is a little decoration on a character such as a short horizontal line at the bottom of the letter i SansSerif means without serifs Monospaced means that all the characters in the font have the same width The Dialog font is the one that is typically used in dialog boxes The style of a font is specified using named constants that are defined in the Font class You can specify the style as one of the four values Font PLAIN Font ITALIC Font BOLD or Font BOLD Font ITALIC The size of a font is an integer Size typically ranges from about 9 to 36 although larger sizes can also be used The size of a font is usually about equal to the height of the largest characters in the font in pixels but this is not an exact rule The size of the default font is 12 Java uses the class named java awt Font for representing fonts You can construct a new font by specifying its font name style and size in a constructor Font plainFont new Font Serif Font PLAIN 12 Font bigBoldFont new Font SansSerif Font BOLD 24 Every graphics context has a current font which is used for drawing text You can change the current font with the setFont method For example if g is a graphics context and bigBoldFont is a font then the command g setFont bigBoldFont will set the current font of g to bigBoldFont The new font will be used for any text that is drawn after the setFont command is given You can find out the current font of g by calling the method g getFont which returns an object of type Font Every component also has an associated font It can be set with the instance method component setFont font which is defined in the Component class When a graphics context is created for drawing on a component the graphic context s current font is set equal to the font of the component 6 2 4 Shapes The Graphics class includes a large number of instance methods for drawing various shapes such as lines rectangles and ovals The shapes are specified using the x y coordinate system described above They are drawn in the current drawing color of the graphics context The current drawing color is set to the foreground color of the component when the graphics context is created but it can be changed at any time using the setColor method Some drawing methods were already listed in Subsection 3 9 1 Here I describe those methods in more detail and add a few more With all these commands any drawing that is done outside the boundaries of the component is ignored Note that all these methods are in the Graphics class so they all must be called through an object of type Graphics It is shown here as g but of course the name of the graphics context is up to the programmer g drawString String str int x int y Draws the text given by the string str The string is drawn using the current color and font of the graphics context x specifies the x coordinate of the left end of the string y is the y coordinate of the baseline of the string The baseline is a horizontal line on which the characters rest Some parts of the characters such as the tail on a y or g extend below the baseline g drawLine int x1 int y1 int x2 int y2 Draws a line from the point x1 y1 to the point x2 y2 The line is drawn as if with a pen that extends one pixel to the right and one pixel down from the x y point where the pen is located For example if g refers to an object of type Graphics then the command g drawLine x y x y which corresponds to putting the pen down at a point colors the single pixel with upper left corner at the point x y Remember that coordinates really refer to the lines between the pixels g drawRect int x int y int width int height Draws the outline of a rectangle The upper left corner is at x y and the width and height of the rectangle are as specified If width equals height then the rectangle is a square If the width or the height is negative then nothing is drawn The rectangle is drawn with the same pen that is used for drawLine This means that the actual width of the rectangle as drawn is width 1 and similarly for the height There is an extra pixel along the right edge and the bottom edge For example if you want to draw a rectangle around the edges of the component you can say g drawRect 0 0 getWidth 1 getHeight 1 If you use g drawRect 0 0 getWidth getHeight then the right and bottom edges of the rectangle will be drawn outside the component and will not appear on the screen g drawOval int x int y int width int height Draws the outline of an oval The oval is one that just fits inside the rectangle specified by x y width and height If width equals height the oval is a circle g drawRoundRect int x int y int width int height int xdiam int ydiam Draws the outline of a rectangle with rounded corners The basic rectangle is specified by x y width and height but the corners are rounded The degree of rounding is given by xdiam and ydiam The corners are arcs of an ellipse with horizontal diameter xdiam and vertical diameter ydiam A typical value for xdiam and ydiam is 16 but the value used should really depend on how big the rectangle is g draw3DRect int x int y int width int height boolean raised Draws the outline of a rectangle that is supposed to have a three dimensional effect as if it is raised from the screen or pushed into the screen The basic rectangle is specified by x y width and height The raised parameter tells whether the rectangle seems to be raised from the screen or pushed into it The 3D effect is achieved by using brighter and darker versions of the drawing color for different edges of the rectangle The documentation recommends setting the drawing color equal to the background color before using this method The effect won t work well for some colors g drawArc int x int y int width int height int startAngle int arcAngle Draws part of the oval that just fits inside the rectangle specified by x y width and height The part drawn is an arc that extends arcAngle degrees from a starting angle at startAngle degrees Angles are measured with 0 degrees at the 3 o clock position the positive direction of the horizontal axis Positive angles are measured counterclockwise from zero and negative angles are measured clockwise To get an arc of a circle make sure that width is equal to height g fillRect int x int y int width int height Draws a filled in rectangle This fills in the interior of the rectangle that would be drawn by drawRect x y width height The extra pixel along the bottom and right edges is not included The width and height parameters give the exact width and height of the rectangle For example if you wanted to fill in the entire component you could say g fillRect 0 0 getWidth getHeight g fillOval int x int y int width int height Draws a filled in oval g fillRoundRect int x int y int width int height int xdiam int ydiam Draws a filled in rounded rectangle g fill3DRect int x int y int width int height boolean raised Draws a filled in three dimensional rectangle g fillArc int x int y int width int height int startAngle int arcAngle Draw a filled in arc This looks like a wedge of pie whose crust is the arc that would be drawn by the drawArc method 6 2 5 Graphics2D All drawing in Java is done through an object of type Graphics The Graphics class provides basic commands for such things as drawing shapes and text and for selecting a drawing color These commands are adequate in many cases but they fall far short of what s needed in a serious computer graphics program Java has another class Graphics2D that provides a larger set of drawing operations Graphics2D is a sub class of Graphics so all the methods from the Graphics class are also available in a Graphics2D The paintComponent method of a JComponent gives you a graphics context of type Graphics that you can use for drawing on the component In fact the graphics context actually belongs to the sub class Graphics2D and can be type cast to gain access to the advanced Graphics2D drawing methods public void paintComponent Graphics g super paintComponent g Graphics2D g2 g2 Graphics2D g Draw on the component using g2 I mention Graphics2D here for completeness I will cover some important aspects of Graphics2D in Section 13 2 but a full treatment is more than we will have time for in this book However there are two simple applications that I would like to start using now without explaining how they work If g2 is a variable of type Graphics2D as in the paintComponent method above then the intimidating looking command g2 setRenderingHint RenderingHints KEY ANTIALIASING RenderingHints VALUE ANTIALIAS ON turns on antialiasing in the graphics context Aliasing is a jagged appearance that can be seen when shapes are drawn using pixels Antialiasing tries to reduce the jaggedness It can make diagonal lines and the outlines of ovals look much nicer It can also improve the appearance of text Another useful command is g2 setStroke new BasicStroke lineWidth where lineWidth is an integer or a float

    Original URL path: http://math.hws.edu/javanotes/c6/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 6.3 -- Mouse Events
    calling the repaint method of the panel For the new version of the program we need an object that implements the MouseListener interface One way to create the object is to define a separate class such as import java awt Component import java awt event An object of type RepaintOnClick is a MouseListener that will respond to a mousePressed event by calling the repaint method of the source of the event That is a RepaintOnClick object can be added as a mouse listener to any Component when the user clicks that component the component will be repainted public class RepaintOnClick implements MouseListener public void mousePressed MouseEvent evt Component source Component evt getSource source repaint Call repaint on the Component that was clicked public void mouseClicked MouseEvent evt public void mouseReleased MouseEvent evt public void mouseEntered MouseEvent evt public void mouseExited MouseEvent evt This class does three of the four things that we need to do in order to handle mouse events First it imports java awt event for easy access to event related classes Second it is declared that the class implements MouseListener And third it provides definitions for the five methods that are specified in the MouseListener interface Note that four of the methods have empty bodies since we don t want to do anything in response to those events We must do one more thing to set up the event handling for this example We must register an event handling object as a listener with the component that will generate the events In this case the mouse events that we are interested in will be generated by an object of type RandomStringsPanel If panel is a variable that refers to the panel object we can create a mouse listener object and register it with the panel with the statements RepaintOnClick listener new RepaintOnClick Create MouseListener object panel addMouseListener listener Register MouseListener with the panel This could be done for example in the main routine where the panel is created Once the listener has been registered in this way it will be notified of mouse events on the panel When a mousePressed event occurs the mousePressed method in the listener will be called The code in this method calls the repaint method in the component that is the source of the event that is in the panel The result is that the RandomStringsPanel is repainted with its strings in new random colors fonts and positions Although we have written the RepaintOnClick class for use with our RandomStringsPanel example the event handling class contains no reference at all to the RandomStringsPanel class How can this be The mousePressed method in class RepaintOnClick looks at the source of the event and calls its repaint method If we have registered the RepaintOnClick object as a listener on a RandomStringsPanel then it is that panel that is repainted But the listener object could be used with any type of component and it would work in the same way Similarly the RandomStringsPanel class contains no reference to the RepaintOnClick class in fact RandomStringsPanel was written before we even knew anything about mouse events The panel will send mouse events to any object that has registered with it as a mouse listener It does not need to know anything about that object except that it is capable of receiving mouse events The relationship between an object that generates an event and an object that responds to that event is rather loose The relationship is set up by registering one object to listen for events from the other object This is something that can potentially be done from outside both objects Each object can be developed independently with no knowledge of the internal operation of the other object This is the essence of modular design Build a complex system out of modules that interact only in straightforward easy to understand ways Then each module is a separate design problem that can be tackled independently Java s event handling framework is designed to offer strong support for modular design To make this clearer let s look at a new version of RandomStrings java the program from Subsection 6 2 7 that uses RandomStringsPanel The new version is ClickableRandomStrings java For convenience I have added RepaintOnClick as a static nested class although it would work just as well as a separate class import java awt Component import java awt event MouseEvent import java awt event MouseListener import javax swing JFrame Displays a window that shows 25 copies of the string Java in random colors fonts and positions The content of the window is an object of type RandomStringsPanel When the user clicks the window the content of the window is repainted with the strings in newly selected random colors fonts and positions public class ClickableRandomStrings public static void main String args JFrame window new JFrame Click Me to Redraw RandomStringsPanel content new RandomStringsPanel content addMouseListener new RepaintOnClick window setContentPane content window setDefaultCloseOperation JFrame EXIT ON CLOSE window setLocation 120 70 window setSize 350 250 window setVisible true private static class RepaintOnClick implements MouseListener public void mousePressed MouseEvent evt Component source Component evt getSource source repaint public void mouseClicked MouseEvent evt public void mouseReleased MouseEvent evt public void mouseEntered MouseEvent evt public void mouseExited MouseEvent evt end class ClickableRandomStrings 6 3 3 MouseEvent Data Often when a mouse event occurs you want to know the location of the mouse cursor This information is available from the MouseEvent parameter to the event handling method which contains instance methods that return information about the event If evt is the parameter then you can find out the coordinates of the mouse cursor by calling evt getX and evt getY These methods return integers which give the x and y coordinates where the mouse cursor was positioned at the time when the event occurred The coordinates are expressed in the coordinate system of the component that generated the event where the top left corner of the component is 0 0 The user can hold down certain modifier keys while using the mouse The possible modifier keys include the Shift key the Control key the Alt key called the Option key on the Mac and the Meta key called the Command or Apple key on the Mac You might want to respond to a mouse event differently when the user is holding down a modifier key The boolean valued instance methods evt isShiftDown evt isControlDown evt isAltDown and evt isMetaDown can be called to test whether the modifier keys are pressed You might also want to have different responses depending on whether the user presses the left mouse button the middle mouse button or the right mouse button For events triggered by a mouse button you can determine which button was pressed or released by calling evt getButton which returns one of the integer constants MouseEvent BUTTON1 MouseEvent BUTTON2 or MouseEvent BUTTON3 for the left middle and right buttons For events such as mouseEntered and mouseExited that are not triggered by buttons evt getButton returns MouseEvent NOBUTTON Now not every mouse has a middle button and a right button and Java deals with that fact in a somewhat peculiar way If the user clicks with the right mouse button then evt isMetaDown will return true even if the user was not holding down the Meta key Similarly if the user clicks with the middle mouse button then evt isAltDown will return true even if the user is not holding down the Alt Option key By using these functions you can design an interface that will work even on computers that lack a middle or right mouse button Note that there is a subtle difference between these functions and evt getButton evt getButton really only applies to mousePressed mouseReleased and mouseClicked events while evt isMetaDown and evt isAltDown are useful in any mouse event I will often use them instead of evt getButton As an example consider a JPanel that does the following Clicking on the panel with the left mouse button will place a red rectangle on the panel at the point where the mouse was clicked Clicking with the right mouse button will place a blue oval on the panel Holding down the Shift key while clicking will clear the panel by removing all the shapes that have been placed You can try the sample program SimpleStamper java Here is what the panel looks like after some shapes have been added There are several ways to write this example There could be a separate class to handle mouse events as in the previous example However in this case I decided to let the panel itself respond to mouse events Any object can be a mouse listener as long as it implements the MouseListener interface In this case the panel class implements the MouseListener interface so the object that represents the main panel of the program can be the mouse listener for the program The constructor for the panel class contains the statement addMouseListener this which is equivalent to saying this addMouseListener this Now the ordinary way to register a mouse listener is to say X addMouseListener Y where Y is the listener and X is the component that will generate the mouse events In the statement addMouseListener this both roles are played by this that is this object the panel is generating mouse events and is also listening for those events Although this might seem a little strange you should get used to seeing things like this In a large program however it s usually a better idea to write a separate class to do the listening in order to have a more organized division of responsibilities The source code for the panel class is shown below I have included a main routine to allow the class to be run as a program as discussed in Subsection 6 2 7 You should check how the instance methods in the MouseEvent object are used You can also check for the Four Steps of Event Handling import java awt event implements MouseListener definitions for the event handling methods and addMouseListener import java awt import java awt event import javax swing A simple demonstration of MouseEvents Shapes are drawn on a black background when the user clicks the panel If the user Shift clicks the panel is cleared If the user right clicks the panel a blue oval is drawn Otherwise when the user clicks a red rectangle is drawn The contents of the panel are not persistent For example they might disappear if the panel is resized This class has a main routine to allow it to be run as an application public class SimpleStamper extends JPanel implements MouseListener public static void main String args JFrame window new JFrame Simple Stamper SimpleStamper content new SimpleStamper window setContentPane content window setDefaultCloseOperation JFrame EXIT ON CLOSE window setLocation 120 70 window setSize 450 350 window setVisible true This constructor simply sets the background color of the panel to be black and sets the panel to listen for mouse events on itself public SimpleStamper setBackground Color BLACK addMouseListener this Since this panel has been set to listen for mouse events on itself this method will be called when the user clicks the mouse on the panel This method is part of the MouseListener interface public void mousePressed MouseEvent evt if evt isShiftDown The user was holding down the Shift key Just repaint the panel Since this class does not define a paintComponent method the method from the superclass JPanel is called That method simply fills the panel with its background color which is black The effect is to clear the panel repaint return int x evt getX x coordinate where user clicked int y evt getY y coordinate where user clicked Graphics g getGraphics Graphics context for drawing directly NOTE This is considered to be bad style if evt isMetaDown User right clicked at the point x y Draw a blue oval centered at the point x y A black outline around the oval will make it more distinct when shapes overlap g setColor Color BLUE Blue interior g fillOval x 30 y 15 60 30 g setColor Color BLACK Black outline g drawOval x 30 y 15 60 30 else User left clicked or middle clicked at x y Draw a red rectangle centered at x y g setColor Color RED Red interior g fillRect x 30 y 15 60 30 g setColor Color BLACK Black outline g drawRect x 30 y 15 60 30 g dispose We are finished with the graphics context so dispose of it end mousePressed The next four empty routines are required by the MouseListener interface They don t do anything in this class so their definitions are empty public void mouseEntered MouseEvent evt public void mouseExited MouseEvent evt public void mouseClicked MouseEvent evt public void mouseReleased MouseEvent evt end class SimpleStamper Note by the way that this class violates the rule that all drawing should be done in a paintComponent method The rectangles and ovals are drawn directly in the mousePressed routine To make this possible I need to obtain a graphics context by saying g getGraphics After using g for drawing I call g dispose to inform the operating system that I will no longer be using g for drawing I do not advise doing this type of direct drawing if it can be avoided but you can see that it does work in this case 6 3 4 MouseMotionListeners and Dragging Whenever the mouse is moved it generates events The operating system of the computer detects these events and uses them to move the mouse cursor on the screen It is also possible for a program to listen for these mouse motion events and respond to them The most common reason to do so is to implement dragging Dragging occurs when the user moves the mouse while holding down a mouse button The methods for responding to mouse motion events are defined in an interface named MouseMotionListener This interface specifies two event handling methods public void mouseDragged MouseEvent evt public void mouseMoved MouseEvent evt The mouseDragged method is called if the mouse is moved while a button on the mouse is pressed If the mouse is moved while no mouse button is down then mouseMoved is called instead The parameter evt is an object of type MouseEvent which contains the x and y coordinates of the mouse s location as usual As long as the user continues to move the mouse one of these methods will be called over and over So many events are generated that it would be inefficient for a program to hear them all if it doesn t want to do anything in response This is why the mouse motion event handlers are defined in a separate interface from the other mouse events You can listen for the mouse events defined in MouseListener without automatically hearing all mouse motion events as well If you want your program to respond to mouse motion events you must create an object that implements the MouseMotionListener interface and you must register that object to listen for events The registration is done by calling a component s addMouseMotionListener method The object will then listen for mouseDragged and mouseMoved events associated with that component In most cases the listener object will also implement the MouseListener interface so that it can respond to the other mouse events as well To get a better idea of how mouse events work you should try the sample program SimpleTrackMouse java This program responds to any of the seven different kinds of mouse events by displaying the coordinates of the mouse the type of event and a list of the modifier keys that are down Shift Control Meta and Alt You can experiment with the program to see what happens as you do various things with the mouse I also encourage you to read the source code You should now be familiar with all the techniques that it uses It is interesting to look at what a program needs to do in order to respond to dragging operations In general the response involves three methods mousePressed mouseDragged and mouseReleased The dragging gesture starts when the user presses a mouse button it continues while the mouse is dragged and it ends when the user releases the button This means that the programming for the response to one dragging gesture must be spread out over the three methods Furthermore the mouseDragged method can be called many times as the mouse moves To keep track of what is going on between one method call and the next you need to set up some instance variables In many applications for example in order to process a mouseDragged event you need to remember the previous coordinates of the mouse You can store this information in two instance variables prevX and prevY of type int It can also be useful to save the starting coordinates where the original mousePressed event occurred in instance variables And I suggest having a boolean variable dragging which is set to true while a dragging gesture is being processed This is necessary because in many applications not every mousePressed event starts a dragging operation to which you want to respond The mouseDragged and mouseReleased methods can use the value of dragging to check whether a drag operation is actually in progress You might need other instance variables as well but in general outline a class that handles mouse dragging looks like this import java awt event public class MouseDragHandler implements MouseListener MouseMotionListener private int startX startY Point where the original mousePress occurred private int prevX prevY Most recently processed mouse coords private boolean dragging Set to true when dragging is in process other instance variables for use in dragging public void mousePressed MouseEvent evt if we want to start dragging dragging true startX evt getX Remember starting position startY evt getY prevX startX Remember most recent coords

    Original URL path: http://math.hws.edu/javanotes/c6/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 6.4 -- Timers, KeyEvents, and State Machines
    presses a button on the mouse the event that is generated is associated with the component that contains the mouse cursor What about keyboard events When the user presses a key what component is associated with the key event that is generated A GUI uses the idea of input focus to determine the component associated with keyboard events At any given time exactly one interface element on the screen has the input focus and that is where all keyboard events are directed If the interface element happens to be a Java component then the information about the keyboard event becomes a Java object of type KeyEvent and it is delivered to any listener objects that are listening for KeyEvents associated with that component The necessity of managing input focus adds an extra twist to working with keyboard events It s a good idea to give the user some visual feedback about which component has the input focus For example if the component is the typing area of a word processor the feedback is usually in the form of a blinking text cursor Another possible visual clue is to draw a brightly colored border around the edge of a component when it has the input focus as I do in the examples given later in this section If comp is any component and you would like it to have the input focus you can call requestFocusInWindow which should work as long as the window that contains the component is active and there is only one component that is requesting focus In some cases when there is only one component involved it is enough to call this method once just after opening the window and the component will retain the focus for the rest of the program Note that there is also a requestFocus method that might work even when the window is not active but the newer method requestFocusInWindow is preferred in most cases In a typical user interface the user can choose to give the focus to a component by clicking on that component with the mouse And pressing the tab key will often move the focus from one component to another This is handled automatically by the components involved without any programming on your part However some components do not automatically request the input focus when the user clicks on them To solve this problem a program can register a mouse listener with the component to detect user clicks In response to a user click the mousePressed method should call requestFocusInWindow for the component This is true in particular for JPanels that are used as drawing surfaces since JPanel objects do not receive the input focus automatically As our first example of processing key events we look at a simple program in which the user moves a square up down left and right by pressing arrow keys When the user hits the R G B or K key the color of the square is set to red green blue or black respectively Of course none of these key events are delivered to the panel unless it has the input focus The panel in the program changes its appearance when it has the input focus When it does a cyan colored border is drawn around the panel when it does not a gray colored border is drawn The complete source code for this example can be found in the file KeyboardAndFocusDemo java I will discuss some aspects of it below After reading this section you should be able to understand the source code in its entirety I suggest running the program to see how it works In Java keyboard event objects belong to a class called KeyEvent An object that needs to listen for KeyEvents must implement the interface named KeyListener Furthermore the object must be registered with a component by calling the component s addKeyListener method The registration is done with the command component addKeyListener listener where listener is the object that is to listen for key events and component is the object that will generate the key events when it has the input focus It is possible for component and listener to be the same object All this is of course directly analogous to what you learned about mouse events in the previous section The KeyListener interface defines the following methods which must be included in any class that implements KeyListener public void keyPressed KeyEvent evt public void keyReleased KeyEvent evt public void keyTyped KeyEvent evt Java makes a careful distinction between the keys that you press and the characters that you type There are lots of keys on a keyboard letter keys number keys modifier keys such as Control and Shift arrow keys page up and page down keys keypad keys function keys and so on In some cases such as the shift key pressing a key does not type a character On the other hand typing a character sometimes involves pressing several keys For example to type an uppercase A you have to press the Shift key and then press the A key before releasing the Shift key On my Mac OS computer I can type an accented e by holding down the Option key pressing the E key releasing the Option key and pressing E again Only one character was typed but I had to perform three key presses and I had to release a key at the right time In Java there are three types of KeyEvent The types correspond to pressing a key releasing a key and typing a character The keyPressed method is called when the user presses a key the keyReleased method is called when the user releases a key and the keyTyped method is called when the user types a character whether that s done with one key press or several Note that one user action such as pressing the E key can be responsible for two events a keyPressed event and a keyTyped event Typing an upper case A can generate two keyPressed events two keyReleased events and one keyTyped event Usually it is better to think in terms of two separate streams of events one consisting of keyPressed and keyReleased events and the other consisting of keyTyped events For some applications you want to monitor the first stream for other applications you want to monitor the second one Of course the information in the keyTyped stream could be extracted from the keyPressed keyReleased stream but it would be difficult and also system dependent to some extent Some user actions such as pressing the Shift key can only be detected as keyPressed events I used to have a computer solitaire game that highlighted every card that could be moved when I held down the Shift key You can do something like that in Java by hiliting the cards when the Shift key is pressed and removing the highlight when the Shift key is released There is one more complication Usually when you hold down a key on the keyboard that key will auto repeat This means that it will generate multiple keyPressed events with just one keyReleased at the end of the sequence It can also generate multiple keyTyped events For the most part this will not affect your programming but you should not expect every keyPressed event to have a corresponding keyReleased event Every key on the keyboard has an integer code number Actually this is only true for keys that Java knows about Many keyboards have extra keys that can t be used with Java When the keyPressed or keyReleased method is called the parameter evt contains the code of the key that was pressed or released The code can be obtained by calling the function evt getKeyCode Rather than asking you to memorize a table of code numbers Java provides a named constant for each key These constants are defined in the KeyEvent class For example the constant for the shift key is KeyEvent VK SHIFT If you want to test whether the key that the user pressed is the Shift key you could say if evt getKeyCode KeyEvent VK SHIFT The key codes for the four arrow keys are KeyEvent VK LEFT KeyEvent VK RIGHT KeyEvent VK UP and KeyEvent VK DOWN Other keys have similar codes The VK stands for Virtual Keyboard In reality different keyboards use different key codes but Java translates the actual codes from the keyboard into its own virtual codes Your program only sees these virtual key codes so it will work with various keyboards on various platforms without modification In the case of a keyTyped event you want to know which character was typed This information can be obtained from the parameter evt in the keyTyped method by calling the function evt getKeyChar This function returns a value of type char representing the character that was typed In the KeyboardAndFocusDemo program I use the keyPressed routine to respond when the user presses one of the arrow keys The program includes instance variables squareLeft and squareTop that give the position of the upper left corner of the movable square When the user presses one of the arrow keys the keyPressed routine modifies the appropriate instance variable and calls repaint to redraw the panel with the square in its new position Note that the values of squareLeft and squareTop are restricted so that the square never moves outside the white area of the panel This is called each time the user presses a key while the panel has the input focus If the key pressed was one of the arrow keys the square is moved except that it is not allowed to move off the edge of the panel allowing for a 3 pixel border public void keyPressed KeyEvent evt int key evt getKeyCode keyboard code for the pressed key if key KeyEvent VK LEFT left arrow key move the square left squareLeft 8 if squareLeft 3 squareLeft 3 repaint else if key KeyEvent VK RIGHT right arrow key move the square right squareLeft 8 if squareLeft getWidth 3 SQUARE SIZE squareLeft getWidth 3 SQUARE SIZE repaint else if key KeyEvent VK UP up arrow key move the square up squareTop 8 if squareTop 3 squareTop 3 repaint else if key KeyEvent VK DOWN down arrow key move the square down squareTop 8 if squareTop getHeight 3 SQUARE SIZE squareTop getHeight 3 SQUARE SIZE repaint end keyPressed Color changes which happen when the user types the characters R G B and K or the lower case equivalents are handled in the keyTyped method I won t include it here since it is so similar to the keyPressed method Finally to complete the KeyListener interface the keyReleased method must be defined In the sample program the body of this method is empty since the program does nothing in response to keyReleased events 6 4 3 Focus Events If a component is to change its appearance when it has the input focus it needs some way to know when it has the focus In Java objects are notified about changes of input focus by events of type FocusEvent An object that wants to be notified of changes in focus can implement the FocusListener interface This interface declares two methods public void focusGained FocusEvent evt public void focusLost FocusEvent evt Furthermore the addFocusListener method must be used to set up a listener for the focus events When a component gets the input focus it calls the focusGained method of any registered with FocusListener When it loses the focus it calls the listener s focusLost method In the sample KeyboardAndFocusDemo program the response to a focus event is simply to redraw the panel The paintComponent method checks whether the panel has the input focus by calling the boolean valued function hasFocus which is defined in the Component class and it draws a different picture depending on whether or not the panel has the input focus The net result is that the appearance of the panel changes when the panel gains or loses focus The methods from the FocusListener interface are defined simply as public void focusGained FocusEvent evt The panel now has the input focus repaint will redraw with a new message and a cyan border public void focusLost FocusEvent evt The panel has now lost the input focus repaint will redraw with a new message and a gray border The other aspect of handling focus is to make sure that the panel actually gets the focus In this case I called requestFocusInWindow for the panel in the program s main routine just after opening the window This approach works because there is only one component in the window and it should have focus as long as the window is active If the user clicks over to another window while using the program the window becomes inactive and the panel loses focus temporarily but gets is back when the user clicks back to the program window There are still decisions to be made about the overall structure of the program In this case I decided to use a nested class named Listener to define an object that listens for both focus and key events In the constructor for the panel I create an object of type Listener and register it to listen for both key events and focus events from the panel See the source code for full details 6 4 4 State Machines The information stored in an object s instance variables is said to represent the state of that object When one of the object s methods is called the action taken by the object can depend on its state Or in the terminology we have been using the definition of the method can look at the instance variables to decide what to do Furthermore the state can change That is the definition of the method can assign new values to the instance variables In computer science there is the idea of a state machine which is just something that has a state and can change state in response to events or inputs The response of a state machine to an event depends on what state it s in when the event occurs An object is a kind of state machine Sometimes this point of view can be very useful in designing classes The state machine point of view can be especially useful in the type of event oriented programming that is required by graphical user interfaces When designing a GUI program you can ask yourself What information about state do I need to keep track of What events can change the state of the program How will my response to a given event depend on the current state Should the appearance of the GUI be changed to reflect a change in state How should the paintComponent method take the state into account All this is an alternative to the top down step wise refinement style of program design which does not apply to the overall design of an event oriented program In the KeyboardAndFocusDemo program shown above the state of the program is recorded in the instance variables squareColor squareLeft and squareTop These state variables are used in the paintComponent method to decide how to draw the panel Their values are changed in the two key event handling methods In the rest of this section we ll look at another example where the state plays an even bigger role In this example the user plays a simple arcade style game by pressing the arrow keys The program is defined in the source code file SubKiller java As usual it would be a good idea to compile and run the program as well as read the full source code Here is a picture The program shows a black submarine near the bottom of the panel While the panel has the input focus this submarine moves back and forth erratically near the bottom Near the top there is a blue boat You can move this boat back and forth by pressing the left and right arrow keys Attached to the boat is a red bomb or depth charge You can drop the bomb by hitting the down arrow key The objective is to blow up the submarine by hitting it with the bomb If the bomb falls off the bottom of the screen you get a new one If the submarine explodes a new sub is created and you get a new bomb Try it Make sure to hit the sub at least once so you can see the explosion Let s think about how this game can be programmed First of all since we are doing object oriented programming I decided to represent the boat the depth charge and the submarine as objects Each of these objects is defined by a separate nested class inside the main panel class and each object has its own state which is represented by the instance variables in the corresponding class I use variables boat bomb and sub in the panel class to refer to the boat bomb and submarine objects Now what constitutes the state of the program That is what things change from time to time and affect the appearance or behavior of the program Of course the state includes the positions of the boat submarine and bomb so those objects have instance variables to store the positions Anything else possibly less obvious Well sometimes the bomb is falling and sometimes it s not That is a difference in state Since there are two possibilities I represent this aspect of the state with a boolean variable in the bomb object bomb isFalling Sometimes the submarine is moving left and sometimes it is moving right The difference is represented by another boolean variable sub isMovingLeft Sometimes the sub is exploding This is also part of the state and it is represented by a boolean variable sub isExploding However the explosions require a little more thought An

    Original URL path: http://math.hws.edu/javanotes/c6/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 6.5 -- Basic Components
    t click on me now 6 5 2 JLabel JLabel is certainly the simplest type of component An object of type JLabel exists just to display a line of text The text cannot be edited by the user although it can be changed by your program The constructor for a JLabel specifies the text to be displayed JLabel message new JLabel Hello World There is another constructor that specifies where in the label the text is located if there is extra space The possible alignments are given by the constants JLabel LEFT JLabel CENTER and JLabel RIGHT For example JLabel message new JLabel Hello World JLabel CENTER creates a label whose text is centered in the available space You can change the text displayed in a label by calling the label s setText method message setText Goodbye World Since the JLabel class is a subclass of JComponent you can use methods such as setForeground and setFont with labels If you want the background color to have any effect you should call setOpaque true on the label since otherwise the JLabel might not fill in its background For example JLabel message new JLabel Hello World JLabel CENTER message setForeground Color RED Display red text message setBackground Color BLACK on a black background message setFont new Font Serif Font BOLD 18 in a big bold font message setOpaque true Make sure background is filled in 6 5 3 JCheckBox A JCheckBox is a component that has two states selected or unselected The user can change the state of a check box by clicking on it The state of a checkbox is represented by a boolean value that is true if the box is selected and is false if the box is unselected A checkbox has a label which is specified when the box is constructed JCheckBox showTime new JCheckBox Show Current Time Usually it s the user who sets the state of a JCheckBox but you can also set the state programmatically The current state of a checkbox is set using its setSelected boolean method For example if you want the checkbox showTime to be checked you would say showTime setSelected true To uncheck the box say showTime setSelected false You can determine the current state of a checkbox by calling its isSelected method which returns a boolean value In many cases you don t need to worry about events from checkboxes Your program can just check the state whenever it needs to know it by calling the isSelected method However a checkbox does generate an event when its state is changed by the user and you can detect this event and respond to it if you want something to happen at the moment the state changes When the state of a checkbox is changed by the user it generates an event of type ActionEvent If you want something to happen when the user changes the state you must register an ActionListener with the checkbox by calling its addActionListener method Note that if you change the state by calling the setSelected method no ActionEvent is generated However there is another method in the JCheckBox class doClick which simulates a user click on the checkbox and does generate an ActionEvent When handling an ActionEvent you can call evt getSource in the actionPerformed method to find out which object generated the event Of course if you are only listening for events from one component you don t have to do this The returned value is of type Object but you can type cast it to another type if you want Once you know the object that generated the event you can ask the object to tell you its current state For example if you know that the event had to come from one of two checkboxes cb1 or cb2 then your actionPerformed method might look like this public void actionPerformed ActionEvent evt Object source evt getSource if source cb1 boolean newState cb1 isSelected respond to the change of state else if source cb2 boolean newState cb2 isSelected respond to the change of state Alternatively you can use evt getActionCommand to retrieve the action command associated with the source For a JCheckBox the action command is by default the label of the checkbox 6 5 4 JTextField and JTextArea The JTextField and JTextArea classes represent components that contain text that can be edited by the user A JTextField holds a single line of text while a JTextArea can hold multiple lines It is also possible to set a JTextField or JTextArea to be read only so that the user can read the text that it contains but cannot edit the text Both classes are subclasses of an abstract class JTextComponent which defines their common properties JTextField and JTextArea have many methods in common The instance method setText which takes a parameter of type String can be used to change the text that is displayed in an input component The contents of the component can be retrieved by calling its getText instance method which returns a value of type String If you want to stop the user from modifying the text you can call setEditable false Call the same method with a parameter of true to make the input component user editable again The user can only type into a text component when it has the input focus The user can give the input focus to a text component by clicking it with the mouse but sometimes it is useful to give the input focus to a text field programmatically You can do this by calling its requestFocusInWindow method For example when I discover an error in the user s input I usually call requestFocusInWindow on the text field that contains the error This helps the user see where the error occurred and lets the user start typing the correction immediately By default there is no space between the text in a text component and the edge of the component which usually doesn t look very

    Original URL path: http://math.hws.edu/javanotes/c6/s5.html (2016-02-07)
    Open archived version from archive