Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Object-Oriented Programming (Java), Unit 17 Kirk Scott.

Similar presentations


Presentation on theme: "1 Object-Oriented Programming (Java), Unit 17 Kirk Scott."— Presentation transcript:

1 1 Object-Oriented Programming (Java), Unit 17 Kirk Scott

2 2 Components, Containers, and Painting 17.1 Components and Containers 17.2 Painting 17.3 Dialog Boxes and String Output to a Panel

3 3 17.1 Components and Containers

4 4 17.1.1 System Classes for Components and Containers Some of the classes in the API for creating graphical user interfaces:

5 5

6 6 17.1.2 Top Level Containers The JFrame, JDialog, and JApplet classes are known as top level containers. They are the basic building blocks for graphical applications. All of the components of a graphical application or applet have to be contained in a top level container. For the graphical applications of this and the following unit, the top level container will be the JFrame. The JPanel class is useful as a sub-container for organizing the elements in a frame.

7 7 17.1.3 The Structure of Top Level Containers A top level container such as a JFrame has a root pane. The root pane manages a layered pane. The layered pane contains a content pane and the menu bar, if there is one. The layered pane has functionality associated with keeping graphical components in order when painting them.

8 The root pane also manages a glass pane. The glass pane “covers” the whole top level container. It has functionality associated with receiving mouse clicks and painting over multiple components. 8

9 9 Here is a diagram of this structure:

10 10 17.1.4 Simple Graphical Applications and Containment Simple applications make use of a JFrame and its content pane: Each top level container has a content pane which is the container for the visible components. Calling getContentPane() on a frame returns a reference to the pane. Every visible component of an application has to be in a containment hierarchy descending from the content pane.

11 Typically, one or more panels are at the top of the hierarchy, contained in the content pane of the frame. A component is put into a container by calling the add() method on the container and passing the component as a parameter. Menus are also important parts of many graphical applications. They are added to the JFrame object of the application, not to the content pane. 11

12 12 17.1.5 The Model-View-Controller Design Pattern The state of an object is contained in its instance variables. This is the model. The representation of an object on the screen is its view.

13 An object may be enabled to respond to user actions like mouse clicks. This functionality is the controller. The model-view-controller design pattern distinguishes between these characteristics when modeling and implementing an application. 13

14 14 17.2 Painting

15 15 17.2.1 System Painting System triggered painting occurs under these three conditions: When the component is first made visible on the screen. When the component is resized. When a component which was wholly or partly covered by another component is uncovered and needs to be repainted. For system supplied components, painting is largely taken care of.

16 16 17.2.2 Painting Methods The JComponent class has several painting methods, which include paint() and paintComponent(). Beginning with the example programs of this unit, the JPanel class will be extended. Graphical applications will be implemented by overriding the paintComponent() method in this subclass.

17 Practical considerations when overriding the paintComponent() method: paintComponent() is defined to take a graphics parameter. The parameter is declared Graphics g. Cast it parameter to Graphics2D. At the top of the overridden method call super.paintComponent(g2). At the end of paintComponent() add the application specific code. 17

18 18 17.2.3 The Callback Mechanism Painting is based on a callback mechanism. This means that painting isn’t accomplished by direct calls to paintComponent(). This is the callback sequence: The state of some object is updated in a program, and the visual representation needs to be updated to reflect that change.

19 A call is made to repaint() on the object in question. repaint() makes a call to update(). This method takes care of housekeeping. repaint() makes a call to the paintComponent() method of the object in question. paintComponent() causes the whole panel to be repainted. This diagram outlines the callback sequence: 19

20 20

21 21 In summary, these are the things that have to be done to support painting in a simple graphical application: Implement a paintComponent() method in a special purpose subclass of the JPanel class. Cast the graphics parameter in paintComponent() and include a call to super.paintComponent(). Put in the painting code appropriate to the application. Place calls to repaint() in the application at points where the state of the application has changed.

22 22 17.3 Dialog Boxes and String Output to a Panel The rest of this unit consists of three example programs, Echo1.java through Echo3.java. The information on the examples is organized as follows: A brief introductory statement summarizing what the application does. Screen shots illustrating what is seen when the application runs. UML diagrams showing the components and structure of the application. Remarks on the contents of the code. The Java code for the application, without comments.

23 23 Echo1 This program shows the use of the system supplied input dialog box. Output is done through a MyTerminalIO object.

24 24

25 25 Only one object is created in the application, myterminal:

26 26 When using the dialog boxes, no object is created. A static method is called on the system supplied JOptionPane class. The showInputDialog() method always brings in a String, so if a numeric type is expected it is necessary to parse the String. The call to exit(0) is not related to the use of the dialog boxes. It is included to illustrate coding an explicit end to a program.

27 27 import javax.swing.*; public class Echo1 { public static void main(String[] args) { String inputString; int inputInt; double inputDouble; double result; MyTerminalIO myterminal = new MyTerminalIO(); inputString = JOptionPane.showInputDialog("Enter a string."); myterminal.println("Here is your string: " + inputString); inputString = JOptionPane.showInputDialog("This time enter an integer."); inputInt = Integer.parseInt(inputString); inputString = JOptionPane.showInputDialog("This time enter a double."); inputDouble = Double.parseDouble(inputString); result = inputInt + inputDouble; myterminal.println("Here is the sum of the values: " + result); inputString = JOptionPane.showInputDialog("Enter anything to quit."); System.exit(0); }

28 28 Echo2 This program shows how to do hardcoded String output into a panel belonging to a frame in an application. It does not literally echo.

29 29 The application has a special purpose frame, Echo2Frame. The frame has a content pane. The application also has a special purpose panel, Echo2Panel, which is a subclass of the JPanel class. An instance of this is added to the frame’s content pane.

30 30

31 31 Here is an outline of the code: In the main() method: An instance of the frame class is constructed. A method is called which sets the default close operation so the application will exit when its frame is closed. The visible property of the frame is set to true.

32 32 In the Echo2Frame class: The frame is given a title. The frame is given a size. An instance of the panel class is constructed. A reference to the content pane of the frame is obtained. The panel is added to the content pane.

33 33 In the Echo2Panel class: The paintComponent() method has a graphics parameter, and this parameter is cast to Graphics2D. A call is made to super.paintComponent(). There is one line of code which calls the graphics method drawstring(), which places a string in the panel, specifying its location by the x and y coordinates of its basepoint. Because the application simply does one thing, there is no chance for its state to change, and there is no call to repaint() in the code.

34 34 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Echo2 { public static void main(String[] args) { Echo2Frame myframe = new Echo2Frame(); myframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); myframe.setVisible(true); }

35 35 class Echo2Frame extends JFrame { public Echo2Frame() { setTitle("Echo2 Frame"); setSize(500, 500); Echo2Panel mypanel = new Echo2Panel(); Container frameContentPane = getContentPane(); frameContentPane.add(mypanel); }

36 36 class Echo2Panel extends JPanel { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paintComponent(g2); g2.drawString("This is hardcoded, not echoed.", 140, 240); }

37 37 Echo3 This is a genuine echoing program. It combines the dialog box input of Echo1 with the panel output of Echo2. The user can repeatedly enter strings into the dialog box as shown, and they are echoed in the panel.

38 38

39 39 The UML diagram shows that the panel has a graphics object in paintComponent(). It also shows that the panel class now has a String instance variable. This is the object which holds the input and allows it to be transferred to output.

40 40

41 41 The program loops in order to continue accepting input. In the main() method the input string is taken in. The setPanelString() method is called on the frame to pass the string to the panel. Inside the setPanelString() method the method setStringToShow() is called on the panel.

42 setStringToShow() does two things: It completes the change of application’s state by assigning the string to the panel's instance variable. It calls repaint(). The callback mechanism causes paintComponent() to be called. paintComponent() contains a call to drawString(), which puts the output in the panel. 42

43 43 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Echo3 { public static void main(String[] args) { String localString = "go"; Echo3Frame myframe = new Echo3Frame(); myframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); myframe.setVisible(true); while(!(localString.equals("quit"))) { localString = OptionPane.showInputDialog ("Enter a string. Enter 'quit' to stop."); myframe.setPanelString(localString); }

44 44 class Echo3Frame extends JFrame { private Echo3Panel mypanel; public Echo3Frame() { setTitle("Echo3 Frame"); setSize(500, 500); mypanel = new Echo3Panel(); Container frameContentPane = getContentPane(); frameContentPane.add(mypanel); } public void setPanelString(String stringIn) { mypanel.setStringToShow(stringIn); }

45 45 class Echo3Panel extends JPanel { private String stringToShow = “”; public void setStringToShow(String stringIn) { stringToShow = stringIn; repaint(); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paintComponent(g2); g2.drawString(stringToShow, 140, 240); }

46 46 WariV23

47 47

48 48 import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Ellipse2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JOptionPane;

49 49 /** This version of Wari goes up through the features illustrated in Echo1 to Echo3. */ public class WariV23 { public static void main(String[] args) { String inputString = "go"; int playCup = 1; WariFrame myFrame = new WariFrame(); myFrame.setTitle("Wari, Version 2.3"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setVisible(true); while(!(inputString.equals("quit"))) { inputString = JOptionPane.showInputDialog("Please enter the number, from 1 to 6,\nof the cup you want to play: "); playCup = Integer.parseInt(inputString); myFrame.playGame(playCup); inputString = JOptionPane.showInputDialog("Enter a string. Enter 'quit' to stop."); }

50 50 class WariFrame extends JFrame { private WariPanel myPanel; private final int FRAMEW = 500; private final int FRAMEH = 500; public WariFrame() { setSize(FRAMEW, FRAMEH); myPanel = new WariPanel(); Container contentPane = getContentPane(); contentPane.add(myPanel, "Center"); } public void playGame(int whichCup) { myPanel.setWhichCup(whichCup); myPanel.playGame(); }

51 51 class WariPanel extends JPanel { private BoardV23 playBoard; private int playTurn; private int whichCupInPanel; public WariPanel() { super(); playTurn = 1; playBoard = new BoardV23(); } public void setWhichCup(int whichCupFromFrame) { whichCupInPanel = whichCupFromFrame; } public void playGame() { playBoard.moveBoard(playTurn, whichCupInPanel); if(playTurn == 1) playTurn = 2; else playTurn = 1; repaint(); }

52 52 public void paintComponent(Graphics g) { BoardLineV23 line1 = new BoardLineV23(); BoardLineV23 line2 = new BoardLineV23(); BoardLineV23 line3 = new BoardLineV23(); BoardLineV23 line4 = new BoardLineV23(); BoardLineV23 line5 = new BoardLineV23(); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; String whoseTurnString = "It's " + playTurn + "'s turn. Enter the cup number in the text box."; g2.drawString(whoseTurnString, 10, 150); playBoard.showBoard(line1, line2, line3, line4, line5); g2.drawString(line1.getLine(), 10, 200); g2.drawString(line2.getLine(), 10, 230); g2.drawString(line3.getLine(), 10, 250); g2.drawString(line4.getLine(), 10, 270); g2.drawString(line5.getLine(), 10, 300); }

53 53 /** This class implements the game board for playing wari. */ public class BoardV23 { private CupV23[][] gameBoard = new CupV23[3][7]; private CupV23[] captured = new CupV23[3];

54 54 /** This constructor sets up the cups in the board, initializing the number of seeds in each to 4, and correctly labelling them as belonging to player 1 or player 2. It also creates the captured cups, initializing the number of seeds in each to 0 and labelling them as belonging to player 1 and player 2 respectively. */ public BoardV23() { captured[1] = new CupV23(0, 1); captured[2] = new CupV23(0, 2); gameBoard[1][6] = new CupV23(4, 1); gameBoard[2][6] = new CupV23(4, 2); for(int i = 5; i > 0; i--) { gameBoard[1][i] = new CupV23(4, 1, gameBoard[1][i + 1]); gameBoard[2][i] = new CupV23(4, 2, gameBoard[2][i + 1]); } gameBoard[1][6].setNextCup(gameBoard[2][1]); gameBoard[2][6].setNextCup(gameBoard[1][1]); }

55 55 /** This method is part of the play. It prints out the the game board in a formatted way, showing the number of seeds in each cup. */ public void showBoard(BoardLineV23 bLine1, BoardLineV23 bLine2, BoardLineV23 bLine3, BoardLineV23 bLine4, BoardLineV23 bLine5) { CupV23 tempReference; int tempSeedCount; bLine1.setLine("Player 1, captured " + captured[1].getSeedCount()); for(int i = 1; i <= 6; i++) { tempReference = gameBoard[2][6]; for(int j = 0; j <= 6 - i; j++) { tempReference = tempReference.getNextCup(); } tempSeedCount = tempReference.getSeedCount(); bLine2.setLine(bLine2.getLine() + " " + tempSeedCount); if(tempSeedCount < 10) bLine2.setLine(bLine2.getLine() + " "); if(i < 6) bLine2.setLine(bLine2.getLine() + " |"); }

56 56 bLine3.setLine("-----------------------------"); tempReference = gameBoard[1][6]; for(int i = 1; i <= 6; i++) { tempReference = tempReference.getNextCup(); tempSeedCount = tempReference.getSeedCount(); bLine4.setLine(bLine4.getLine() + " " + tempSeedCount); if(tempSeedCount < 10) bLine4.setLine(bLine4.getLine() + " "); if(i < 6) bLine4.setLine(bLine4.getLine() + " |"); } bLine5.setLine("Player 2, captured " + captured[2].getSeedCount()); }

57 57 /** This method implements the actual playing of a move in wari. @param whoseTurn tells which player's turn it is who is playing. @param whichCup tells which cup the player has chosen to play. */ public void moveBoard(int whoseTurn, int whichCup) { int handfull = gameBoard[whoseTurn][whichCup].removeSeeds(); CupV23 tempReference = gameBoard[whoseTurn][whichCup].getNextCup(); while(handfull != 0) { tempReference.addOneSeed(); handfull--; if(tempReference.getWhoseCup() != whoseTurn) { if(tempReference.getSeedCount() == 2 || tempReference.getSeedCount() == 3) { captured[whoseTurn].addSomeSeeds(tempReference.removeSeeds()); } tempReference = tempReference.getNextCup(); }

58 58 public class BoardLineV23 { private String theLine; public BoardLineV23() { theLine = ""; } public void setLine(String lineIn) { theLine = lineIn; } public String getLine() { return theLine; }

59 59 /** The Cup class is used to create the 12 cups of the wari Board, as well as the two additional cups for keeping a count of the number of seeds captured, one for each player. */ public class CupV23 { private int seedCount; private int whoseCup; private CupV23 nextCup; /** This constructor is used for creating the captured cups. There are no links between these cups. @param seedCountin is an integer that initializes the number of seeds in the cup. @param whoseCupin is an integer that identifies which player the cup belongs to, player 1 or player 2. */ public CupV23(int seedCountin, int whoseCupin) { seedCount = seedCountin; whoseCup = whoseCupin; nextCup = null; }

60 60 /** This constructor is used for creating the 12 cups that are part of the wari Board. @param seedCountin is an integer that initializes the number of seeds in the cup. @param whoseCupin is an integer that identifies which player the cup belongs to, player 1 or player 2. @param nextCupin contains a reference to another cup on the board. Not only are the cups related by their position in an array, for good measure they are linked together in their order of play. */ public CupV23(int seedCountin, int whoseCupin, CupV23 nextCupin) { seedCount = seedCountin; whoseCup = whoseCupin; nextCup = nextCupin; }

61 61 /** This method is an incomplete implementation of the standard toString() method. It is incomplete because only the count of the number of seeds and who the cup belongs to are printed out. No information on the next cup in the board is printed out. @return String is a String containing the count of the number of seeds and a number indicating who the cup belonged to. */ public String toString() { return "Cup[seedCount = " + seedCount + ", whoseCup = " + whoseCup + "]"; }

62 62 /** This method simply returns the count of the number of seeds in the cup. @return this is the count of the seeds. */ public int getSeedCount() { return seedCount; } /** This method adds one to the count of seeds in a cup. This is used as play progresses and seeds are dropped around the board one by one. */ public void addOneSeed() { seedCount++; }

63 63 /** This method adds the amount given as a parameter to the number of seeds in a cup. It is used when a player captures some seeds and they are put into that player's captured cup. @param seedsin is the number of seeds to add to the cup. */ public void addSomeSeeds(int seedsin) { seedCount += seedsin; } /** This method simply returns the integer, 1 or 2, telling which player the cup belongs to. @return the player the cup belongs to. */ public int getWhoseCup() { return whoseCup; }

64 64 /** This method returns a reference to the next cup in the game board. @return the next game cup in the board. */ public CupV23 getNextCup() { return nextCup; } /** This method sets the value of the instance variable that holds the reference to the next cup in the game board. It is called when the Board class constructor is creating the cups and arranging them in an instance of the board. @param nextCupin is the reference to the next cup in the board. */ public void setNextCup(CupV23 nextCupin) { nextCup = nextCupin; }

65 65 /** This method zeros out the count of the number of seeds in a cup and returns that number. It is used in play when a capture occurs. @return the number of seeds that were in the cup. */ public int removeSeeds() { int temp = seedCount; seedCount = 0; return temp; }

66 Java Unit 17 Assignment Grading check-off checklist: This checklist is largely a repetition of the assignment. It is given here because this is the summary, in words, which I refer to when checking off assignments. You should have a version of Togiz Kumalak which compiles and runs. 66

67 1. This version of Togiz Kumalak should take in input through a separate, non- integrated text box. 2. It should display output in an integrated graphical panel. 3. The seed counts should be represented by digits. 4. For full credit, you should also have a UML diagram for your program. 67

68 68 1. Write a version of Togiz Kumalak that includes the graphical features that are illustrated in example programs Echo1.java through Echo3.java. Your application should take input from an input dialog box and produce a Unicode oriented representation of the game board, with numbers for the seed counts in the cups.

69 The presentation of the game board should be similar to its appearance in the non-graphical version you wrote as part of the assignment for Unit 15. The difference is that it no longer uses MyTerminalIO. It takes in input through its own dialog box, and presents the board and its contents in its own graphical frame and panel. Draw a UML diagram for your solution. 69

70 70 You can do this assignment by modifying WariV23. You can also do this assignment by modifying the code you wrote for assignment 15. Your program should play the Togiz Kumalak rules and have the same graphical features that WariV23 has.

71 71 The End


Download ppt "1 Object-Oriented Programming (Java), Unit 17 Kirk Scott."

Similar presentations


Ads by Google