SlideShare a Scribd company logo
1 of 13
Download to read offline
Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from
JPanel. Therefore, the panel you are asked to add to the center of the content pane is the "game"
object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book,
but it is mentioned in the framework comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel
{
private JButton [][] squares;
private TilePuzzle game;
public Game( int newSide )
{
game = new TilePuzzle( newSide );
setUpGameGUI( );
}
public void setUpGame( int newSide )
{
game.setUpGame( newSide );
setUpGameGUI( );
}
public void setUpGameGUI( )
{
removeAll( ); // remove all components
setLayout( new GridLayout( game.getSide( ),
game.getSide( ) ) );
squares = new JButton[game.getSide( )][game.getSide( )];
ButtonHandler bh = new ButtonHandler( );
// for each button: generate button label,
// instantiate button, add to container,
// and register listener
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j] = new JButton( game.getTiles( )[i][j] );
add( squares[i][j] );
squares[i][j].addActionListener( bh );
}
}
setSize( 300, 300 );
setVisible( true );
}
private void update( int row, int col )
{
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j].setText( game.getTiles( )[i][j] );
}
}
if ( game.won( ) )
{
JOptionPane.showMessageDialog( Game.this,
"Congratulations! You won! Setting up new game" );
// int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) );
// setUpGameGUI( );
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for( int i = 0; i < game.getSide( ); i++ )
{
for( int j = 0; j < game.getSide( ); j++ )
{
if ( ae.getSource( ) == squares[i][j] )
{
if ( game.tryToPlay( i, j ) )
update( i, j );
return;
} // end if
} // end inner for loop
} // outer for loop
} // end actionPerformed method
} // end ButtonHandler class
} // end Game class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super("Practicing layout managers");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel("Have fun playing this Tile Puzzle game",
SwingConstants.CENTER);
// ***** Task 3:
// instantiate the JPanel component named top
// Part 3 student code starts here:
// set the layout of top to a 1-by-3 grid
// instantiate the JButtons that determine the grid size
// add the buttons to JPanel top
// add JPanel top to the content pane as its north component
// Part 3 student code ends here.
// ***** Task 5:
// Note: search for and complete Task 4 before performing this task
// Part 5 student code starts here:
// declare and instantiate an ActionListener
// register the listener on the 3 buttons
// that you declared in Task 1
// Part 5 student code ends here.
contents.add(bottom, BorderLayout.SOUTH);
setSize(325, 325);
setVisible(true);
}
// ***** Task 4:
// create a private inner class that implements ActionListener
// your method should identify which of the 3 buttons
// was the source of the event
// depending on which button was pressed,
// call the setUpGame method of the Game class
// with arguments 3, 4, or 5
// the API of that method is:
// public void setUpGame(int nSides)
// At the end of the method call validate()
// Part 4 student code starts here:
// Part 4 student code ends here.
public static void main(String[] args)
{
NestedLayoutPractice nl = new NestedLayoutPractice();
nl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class TilePuzzle
{
private int side; // grid size for game 1
private String[][] tiles;
private int emptyRow;
private int emptyCol;
public TilePuzzle( int newSide )
{
setUpGame( newSide );
}
public void setUpGame( int newSide )
{
if ( side > 0 )
side = newSide;
else
side = 3;
side = newSide;
tiles = new String[side][side];
emptyRow = side - 1;
emptyCol = side - 1;
for ( int i = 0; i < side; i++ )
{
for ( int j = 0; j < side; j++ )
{
tiles[i][j] = String.valueOf( ( side * side )
- ( side * i + j + 1 ) );
}
}
// set empty tile to blank
tiles[side - 1][side - 1] = "";
}
public int getSide( )
{
return side;
}
/*
public int getEmptyRow( )
{
return emptyRow;
}
public int getEmptyCol( )
{
return emptyCol;
}
*/
public String[][] getTiles( )
{
return tiles;
}
public boolean tryToPlay( int row, int col )
{
if ( possibleToPlay( row, col ) )
{
// play: switch empty String and tile label at row, col
tiles[emptyRow][emptyCol] = tiles[row][col];
tiles[row][col] = "";
emptyRow = row;
emptyCol = col;
return true;
}
else
return false;
}
public boolean possibleToPlay( int row, int col )
{
if ( ( col == emptyCol && Math.abs( row - emptyRow ) == 1 )
|| ( row == emptyRow && Math.abs( col - emptyCol ) == 1 ) )
return true;
else
return false;
}
public boolean won( )
{
for ( int i = 0; i < side ; i++ )
{
for ( int j = 0; j < side; j++ )
{
if ( !( tiles[i][j].equals(
String.valueOf( i * side + j + 1 ) ) )
&& ( i != side - 1 || j != side - 1 ) )
return false;
}
}
return true;
}
}
Programming Activity 12-2 Guidance
==================================
Overview
--------
There are 5 parts.
Make sure you complete the parts in numerical order.
Notice that part 4 occurs in the code after part 5.
As stated in the part 5 comments, you should complete part 4 before
part 5 because part 5 has a step that says:
"// declare and instantiate an ActionListener"
This ActionListener must be an object of the private inner button handler class
that you write in part 4.
The 5 parts of 12-2 each have helpful comments.
The comments will guide you about what code to write.
Button instantiation
--------------------
Suppose you define a button as follows:
JButton three;
To instantiate it with its label set to "3 x 3", you would write:
three = new JButton("3 x 3");
Part 2
------
Note that the Game class inherits from JPanel.
Therefore, the panel you are asked to add to the center of the
content pane is the "game" object.
Part 4 button handler
---------------------
You have to create a private inner class to handle events from any
of the three game setup buttons.
This course is cumulative. Each new chapter builds on previous chapters.
Week 4 had a video called Java GUI Button Components.
The code for that video was supplied in a folder in week 4.
Here is a section of the code shown in that video:
private class CommandHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == btnDisplayTrees)
{
displayTrees();
return;
}
if (source == btnDisplayWater)
{
displayWater();
return;
}
if (source == btnPackWindow)
{
packWindow();
return;
}
if (source == btnReset)
{
reset();
return;
}
}
etc.
The above code shows a private inner class named CommandHandler that
handles button events. You can name your button handler whatever you want,
such as ButtonHandler, but you must use the same name in part 5 after the comment:
// declare and instantiate an ActionListener
In the above video example, there is an if test for each button event.
Each of the if blocks does something and then returns.
In your button handler, you also have to do a certain thing for each button
as specified in the comments. However, you cannot then simply return because
validate() must be called at the end of the function--no matter which button
was clicked. There are 2 simple ways to achieve this:
1) Use nested if/else's followed by the validate() call, or
2) Call validate() after each button's processing and then return
from each one as in the video example.
Part 4 setUpGame()
------------------
The part 4 comments include:
// depending on which button was pressed,
// call the setUpGame method of the Game class
// with arguments 3, 4, or 5
// the API of that method is:
// public void setUpGame(int nSides)
To call a function we need an object of its class.
Does our framework code have an object for us of type Game?
Looking near the beginning of the NestedLayoutPractice class
that we are in, you will see the following declaration:
private Game game;
So, game is an object reference of type Game that we can use.
Your framework starting code already includes the following line
of code in part 2:
game = new Game(3); // instantiating the GamePanel object
This is where the game object is actually created. It is passed
a value of 3 in the constructor call. This will cause the game
to be created with 3 rows by 3 columns of numbered squares.
Now back to your part 4 handler comments. The comments say to change
the game setup as instructed based on which button was clicked.
If you look at the example user interface you will see that there
are 3 buttons to change the game to 3 x 3, or 4 x 4, or 5 x 5 squares.
You should have already declared these buttons in part 1 and created
them in part 3 as instructed.
In part 4, your event handler function must handle when each of the
buttons is clicked. If, for exaample, the 4 x 4 button is clicked, then
you should have the following line of code for that event:
game.setUpGame(4);
Don't overthink this. It is a simple function call using the game
object, its setUpGame() method, and a literal parameter of 4.
At the end of the function, call
Solution
NestedLayoutPractice.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
private JPanel top;
private JButton btnDisplayTrees;
private JButton btnDisplayWater;
private JButton btnPackWindow;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice(){
super("Practicing layout managers");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
bl = new BorderLayout();
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:-------
bl.layoutContainer(contents);
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
contents.add(game);
// Part 2 student code ends here.
bottom = new JLabel("Have fun playing this Tile Puzzle game",
SwingConstants.CENTER);
// ***** Task 3:
// instantiate the JPanel component named top
top = new JPanel();
// Part 3 student code starts here:
top.setLayout(new GridLayout(1, 3, 5, 5));
// set the layout of top to a 1-by-3 grid--------
// instantiate the JButtons that determine the grid size
btnDisplayTrees = new JButton("3 x 3");
btnDisplayWater = new JButton("4 x 4");
btnPackWindow = new JButton("5 x 5");
// add the buttons to JPanel top
top.add(btnDisplayTrees);
top.add(btnDisplayWater);
top.add(btnPackWindow);
// add JPanel top to the content pane as its north component
top.add(contents,BorderLayout.NORTH);
// Part 3 student code ends here.
// ***** Task 5:
// Note: search for and complete Task 4 before performing this task
// Part 5 student code starts here:
// declare and instantiate an ActionListener
CommandHandler ch = new CommandHandler();
// register the listener on the 3 buttons
btnDisplayTrees.addActionListener(ch);
btnDisplayWater.addActionListener(ch);
btnPackWindow.addActionListener(ch);
// that you declared in Task 1
// Part 5 student code ends here.
contents.add(bottom, BorderLayout.SOUTH);
setSize(325, 325);
setVisible(true);
}
// ***** Task 4:
// create a private inner class that implements ActionListener
// your method should identify which of the 3 buttons
// was the source of the event
// depending on which button was pressed,
// call the setUpGame method of the Game class
// with arguments 3, 4, or 5
// the API of that method is:
// public void setUpGame(int nSides)
// At the end of the method call validate()
// Part 4 student code starts here:
// Part 4 student code ends here.
private class CommandHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source == btnDisplayTrees){
//displayTrees();
game.setUpGame(3);
game.validate();
return;
}
if (source == btnDisplayWater){
// displayWater();
game.setUpGame(4);
game.validate();
return;
}
if (source == btnPackWindow){
//packWindow();
game.setUpGame(5);
game.validate();
return;
}
// if (source == btnReset){
// reset();
// return;
// }
}
}
public static void main(String[] args){
NestedLayoutPractice nl = new NestedLayoutPractice();
nl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

More Related Content

Similar to Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf

I really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdfI really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdfaggarwalshoppe14
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmccormicknadine86
 
#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docxadkinspaige22
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfinfomalad
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfaakarcreations1
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfformaxekochi
 
Hi my question pretains to Java programing, What I am creating is a .pdf
Hi my question pretains to Java programing, What I am creating is a .pdfHi my question pretains to Java programing, What I am creating is a .pdf
Hi my question pretains to Java programing, What I am creating is a .pdfeyeonsecuritysystems
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfseamusschwaabl99557
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
CalculatorProject.pdf
CalculatorProject.pdfCalculatorProject.pdf
CalculatorProject.pdfblueline4
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino Giuseppe Modarelli
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
 
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)Games, AI, and Research - Part 2 Training (FightingICE AI Programming)
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)Pujana Paliyawan
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 

Similar to Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf (20)

I really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdfI really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdf
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
Graphical User Components Part 2
Graphical User Components Part 2Graphical User Components Part 2
Graphical User Components Part 2
 
#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx#include iostream#include fstream#include Opening.h.docx
#include iostream#include fstream#include Opening.h.docx
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdf
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdfTic Tac Toe game with GUI please dont copy and paste from google. .pdf
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
 
Hi my question pretains to Java programing, What I am creating is a .pdf
Hi my question pretains to Java programing, What I am creating is a .pdfHi my question pretains to Java programing, What I am creating is a .pdf
Hi my question pretains to Java programing, What I am creating is a .pdf
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
ch20.pptx
ch20.pptxch20.pptx
ch20.pptx
 
CalculatorProject.pdf
CalculatorProject.pdfCalculatorProject.pdf
CalculatorProject.pdf
 
Html5 game, websocket e arduino
Html5 game, websocket e arduino Html5 game, websocket e arduino
Html5 game, websocket e arduino
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)Games, AI, and Research - Part 2 Training (FightingICE AI Programming)
Games, AI, and Research - Part 2 Training (FightingICE AI Programming)
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 

More from udit652068

Discuss briefly and with examples, What key measures need to be take.pdf
Discuss briefly and with examples, What key measures need to be take.pdfDiscuss briefly and with examples, What key measures need to be take.pdf
Discuss briefly and with examples, What key measures need to be take.pdfudit652068
 
Did BP respond in a manner that was appropriate with the oil spill t.pdf
Did BP respond in a manner that was appropriate with the oil spill t.pdfDid BP respond in a manner that was appropriate with the oil spill t.pdf
Did BP respond in a manner that was appropriate with the oil spill t.pdfudit652068
 
Describe and provide at least two examples of direct transmission of.pdf
Describe and provide at least two examples of direct transmission of.pdfDescribe and provide at least two examples of direct transmission of.pdf
Describe and provide at least two examples of direct transmission of.pdfudit652068
 
Define VRIO in business strategy Define VRIO in business strat.pdf
Define VRIO in business strategy Define VRIO in business strat.pdfDefine VRIO in business strategy Define VRIO in business strat.pdf
Define VRIO in business strategy Define VRIO in business strat.pdfudit652068
 
Define e-commerce and describe how it differs from e-business.So.pdf
Define e-commerce and describe how it differs from e-business.So.pdfDefine e-commerce and describe how it differs from e-business.So.pdf
Define e-commerce and describe how it differs from e-business.So.pdfudit652068
 
Building Social Business - EssaySolutionBuilding social busine.pdf
Building Social Business - EssaySolutionBuilding social busine.pdfBuilding Social Business - EssaySolutionBuilding social busine.pdf
Building Social Business - EssaySolutionBuilding social busine.pdfudit652068
 
You are to write a C++ program to produce an inventory repor.pdf
You are to write a C++ program to produce an inventory repor.pdfYou are to write a C++ program to produce an inventory repor.pdf
You are to write a C++ program to produce an inventory repor.pdfudit652068
 
Write a java program that would ask the user to enter an input file .pdf
Write a java program that would ask the user to enter an input file .pdfWrite a java program that would ask the user to enter an input file .pdf
Write a java program that would ask the user to enter an input file .pdfudit652068
 
Which of the following defines a method doubleEach that returns an ar.pdf
Which of the following defines a method doubleEach that returns an ar.pdfWhich of the following defines a method doubleEach that returns an ar.pdf
Which of the following defines a method doubleEach that returns an ar.pdfudit652068
 
When the Fed provides more reserves toprovides more reserves to.pdf
When the Fed provides more reserves toprovides more reserves to.pdfWhen the Fed provides more reserves toprovides more reserves to.pdf
When the Fed provides more reserves toprovides more reserves to.pdfudit652068
 
What is a common infrastructure and what does it provideSolutio.pdf
What is a common infrastructure and what does it provideSolutio.pdfWhat is a common infrastructure and what does it provideSolutio.pdf
What is a common infrastructure and what does it provideSolutio.pdfudit652068
 
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdf
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdfWhat are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdf
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdfudit652068
 
What are some of the commonly seen WLAN devices What role does each.pdf
What are some of the commonly seen WLAN devices What role does each.pdfWhat are some of the commonly seen WLAN devices What role does each.pdf
What are some of the commonly seen WLAN devices What role does each.pdfudit652068
 
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdf
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdfUsing the header(dlist) and mainline file (dlistapp) belowYou are .pdf
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdfudit652068
 
Virology.Explain the make up and role of different complexes for .pdf
Virology.Explain the make up and role of different complexes for .pdfVirology.Explain the make up and role of different complexes for .pdf
Virology.Explain the make up and role of different complexes for .pdfudit652068
 
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdf
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdfTOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdf
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdfudit652068
 
These are the outputs which should match they are 4 of them -outp.pdf
These are the outputs which should match they are 4 of them -outp.pdfThese are the outputs which should match they are 4 of them -outp.pdf
These are the outputs which should match they are 4 of them -outp.pdfudit652068
 
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdf
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdfThe test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdf
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdfudit652068
 
The selection of officials in which of the following branches of the.pdf
The selection of officials in which of the following branches of the.pdfThe selection of officials in which of the following branches of the.pdf
The selection of officials in which of the following branches of the.pdfudit652068
 
the distance between the N-terminal and C-ternimal amino acids varie.pdf
the distance between the N-terminal and C-ternimal amino acids varie.pdfthe distance between the N-terminal and C-ternimal amino acids varie.pdf
the distance between the N-terminal and C-ternimal amino acids varie.pdfudit652068
 

More from udit652068 (20)

Discuss briefly and with examples, What key measures need to be take.pdf
Discuss briefly and with examples, What key measures need to be take.pdfDiscuss briefly and with examples, What key measures need to be take.pdf
Discuss briefly and with examples, What key measures need to be take.pdf
 
Did BP respond in a manner that was appropriate with the oil spill t.pdf
Did BP respond in a manner that was appropriate with the oil spill t.pdfDid BP respond in a manner that was appropriate with the oil spill t.pdf
Did BP respond in a manner that was appropriate with the oil spill t.pdf
 
Describe and provide at least two examples of direct transmission of.pdf
Describe and provide at least two examples of direct transmission of.pdfDescribe and provide at least two examples of direct transmission of.pdf
Describe and provide at least two examples of direct transmission of.pdf
 
Define VRIO in business strategy Define VRIO in business strat.pdf
Define VRIO in business strategy Define VRIO in business strat.pdfDefine VRIO in business strategy Define VRIO in business strat.pdf
Define VRIO in business strategy Define VRIO in business strat.pdf
 
Define e-commerce and describe how it differs from e-business.So.pdf
Define e-commerce and describe how it differs from e-business.So.pdfDefine e-commerce and describe how it differs from e-business.So.pdf
Define e-commerce and describe how it differs from e-business.So.pdf
 
Building Social Business - EssaySolutionBuilding social busine.pdf
Building Social Business - EssaySolutionBuilding social busine.pdfBuilding Social Business - EssaySolutionBuilding social busine.pdf
Building Social Business - EssaySolutionBuilding social busine.pdf
 
You are to write a C++ program to produce an inventory repor.pdf
You are to write a C++ program to produce an inventory repor.pdfYou are to write a C++ program to produce an inventory repor.pdf
You are to write a C++ program to produce an inventory repor.pdf
 
Write a java program that would ask the user to enter an input file .pdf
Write a java program that would ask the user to enter an input file .pdfWrite a java program that would ask the user to enter an input file .pdf
Write a java program that would ask the user to enter an input file .pdf
 
Which of the following defines a method doubleEach that returns an ar.pdf
Which of the following defines a method doubleEach that returns an ar.pdfWhich of the following defines a method doubleEach that returns an ar.pdf
Which of the following defines a method doubleEach that returns an ar.pdf
 
When the Fed provides more reserves toprovides more reserves to.pdf
When the Fed provides more reserves toprovides more reserves to.pdfWhen the Fed provides more reserves toprovides more reserves to.pdf
When the Fed provides more reserves toprovides more reserves to.pdf
 
What is a common infrastructure and what does it provideSolutio.pdf
What is a common infrastructure and what does it provideSolutio.pdfWhat is a common infrastructure and what does it provideSolutio.pdf
What is a common infrastructure and what does it provideSolutio.pdf
 
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdf
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdfWhat are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdf
What are the eukaryotic kingdomsQuestion 4 optionsBacteria, Ar.pdf
 
What are some of the commonly seen WLAN devices What role does each.pdf
What are some of the commonly seen WLAN devices What role does each.pdfWhat are some of the commonly seen WLAN devices What role does each.pdf
What are some of the commonly seen WLAN devices What role does each.pdf
 
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdf
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdfUsing the header(dlist) and mainline file (dlistapp) belowYou are .pdf
Using the header(dlist) and mainline file (dlistapp) belowYou are .pdf
 
Virology.Explain the make up and role of different complexes for .pdf
Virology.Explain the make up and role of different complexes for .pdfVirology.Explain the make up and role of different complexes for .pdf
Virology.Explain the make up and role of different complexes for .pdf
 
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdf
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdfTOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdf
TOPOLOGY 541Let M be a set with two members a and b. Define the fu.pdf
 
These are the outputs which should match they are 4 of them -outp.pdf
These are the outputs which should match they are 4 of them -outp.pdfThese are the outputs which should match they are 4 of them -outp.pdf
These are the outputs which should match they are 4 of them -outp.pdf
 
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdf
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdfThe test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdf
The test solution is made basic and drops of 0.1 M Ca(NO3)2 are adde.pdf
 
The selection of officials in which of the following branches of the.pdf
The selection of officials in which of the following branches of the.pdfThe selection of officials in which of the following branches of the.pdf
The selection of officials in which of the following branches of the.pdf
 
the distance between the N-terminal and C-ternimal amino acids varie.pdf
the distance between the N-terminal and C-ternimal amino acids varie.pdfthe distance between the N-terminal and C-ternimal amino acids varie.pdf
the distance between the N-terminal and C-ternimal amino acids varie.pdf
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf

  • 1. Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from JPanel. Therefore, the panel you are asked to add to the center of the content pane is the "game" object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book, but it is mentioned in the framework comments. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Game extends JPanel { private JButton [][] squares; private TilePuzzle game; public Game( int newSide ) { game = new TilePuzzle( newSide ); setUpGameGUI( ); } public void setUpGame( int newSide ) { game.setUpGame( newSide ); setUpGameGUI( ); } public void setUpGameGUI( ) { removeAll( ); // remove all components setLayout( new GridLayout( game.getSide( ), game.getSide( ) ) ); squares = new JButton[game.getSide( )][game.getSide( )]; ButtonHandler bh = new ButtonHandler( ); // for each button: generate button label, // instantiate button, add to container, // and register listener for ( int i = 0; i < game.getSide( ); i++ ) { for ( int j = 0; j < game.getSide( ); j++ ) {
  • 2. squares[i][j] = new JButton( game.getTiles( )[i][j] ); add( squares[i][j] ); squares[i][j].addActionListener( bh ); } } setSize( 300, 300 ); setVisible( true ); } private void update( int row, int col ) { for ( int i = 0; i < game.getSide( ); i++ ) { for ( int j = 0; j < game.getSide( ); j++ ) { squares[i][j].setText( game.getTiles( )[i][j] ); } } if ( game.won( ) ) { JOptionPane.showMessageDialog( Game.this, "Congratulations! You won! Setting up new game" ); // int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) ); // setUpGameGUI( ); } } private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent ae ) { for( int i = 0; i < game.getSide( ); i++ ) { for( int j = 0; j < game.getSide( ); j++ ) { if ( ae.getSource( ) == squares[i][j] ) { if ( game.tryToPlay( i, j ) )
  • 3. update( i, j ); return; } // end if } // end inner for loop } // outer for loop } // end actionPerformed method } // end ButtonHandler class } // end Game class import javax.swing.*; import java.awt.*; import java.awt.event.*; public class NestedLayoutPractice extends JFrame { private Container contents; private Game game; private BorderLayout bl; private JLabel bottom; // ***** Task 1: declare a JPanel named top // also declare three JButton instance variables // that will be added to the JPanel top // these buttons will determine the grid size of the game: // 3-by-3, 4-by-4, or 5-by-5 // Part 1 student code starts here: // Part 1 student code ends here. public NestedLayoutPractice() { super("Practicing layout managers"); contents = getContentPane(); // ***** Task 2: // instantiate the BorderLayout manager bl // Part 2 student code starts here: // set the layout manager of the content pane contents to bl: game = new Game(3); // instantiating the GamePanel object // add panel (game) to the center of the content pane // Part 2 student code ends here. bottom = new JLabel("Have fun playing this Tile Puzzle game",
  • 4. SwingConstants.CENTER); // ***** Task 3: // instantiate the JPanel component named top // Part 3 student code starts here: // set the layout of top to a 1-by-3 grid // instantiate the JButtons that determine the grid size // add the buttons to JPanel top // add JPanel top to the content pane as its north component // Part 3 student code ends here. // ***** Task 5: // Note: search for and complete Task 4 before performing this task // Part 5 student code starts here: // declare and instantiate an ActionListener // register the listener on the 3 buttons // that you declared in Task 1 // Part 5 student code ends here. contents.add(bottom, BorderLayout.SOUTH); setSize(325, 325); setVisible(true); } // ***** Task 4: // create a private inner class that implements ActionListener // your method should identify which of the 3 buttons // was the source of the event // depending on which button was pressed, // call the setUpGame method of the Game class // with arguments 3, 4, or 5 // the API of that method is: // public void setUpGame(int nSides) // At the end of the method call validate() // Part 4 student code starts here: // Part 4 student code ends here. public static void main(String[] args) { NestedLayoutPractice nl = new NestedLayoutPractice(); nl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  • 5. } } public class TilePuzzle { private int side; // grid size for game 1 private String[][] tiles; private int emptyRow; private int emptyCol; public TilePuzzle( int newSide ) { setUpGame( newSide ); } public void setUpGame( int newSide ) { if ( side > 0 ) side = newSide; else side = 3; side = newSide; tiles = new String[side][side]; emptyRow = side - 1; emptyCol = side - 1; for ( int i = 0; i < side; i++ ) { for ( int j = 0; j < side; j++ ) { tiles[i][j] = String.valueOf( ( side * side ) - ( side * i + j + 1 ) ); } } // set empty tile to blank tiles[side - 1][side - 1] = ""; } public int getSide( ) { return side;
  • 6. } /* public int getEmptyRow( ) { return emptyRow; } public int getEmptyCol( ) { return emptyCol; } */ public String[][] getTiles( ) { return tiles; } public boolean tryToPlay( int row, int col ) { if ( possibleToPlay( row, col ) ) { // play: switch empty String and tile label at row, col tiles[emptyRow][emptyCol] = tiles[row][col]; tiles[row][col] = ""; emptyRow = row; emptyCol = col; return true; } else return false; } public boolean possibleToPlay( int row, int col ) { if ( ( col == emptyCol && Math.abs( row - emptyRow ) == 1 ) || ( row == emptyRow && Math.abs( col - emptyCol ) == 1 ) ) return true; else return false;
  • 7. } public boolean won( ) { for ( int i = 0; i < side ; i++ ) { for ( int j = 0; j < side; j++ ) { if ( !( tiles[i][j].equals( String.valueOf( i * side + j + 1 ) ) ) && ( i != side - 1 || j != side - 1 ) ) return false; } } return true; } } Programming Activity 12-2 Guidance ================================== Overview -------- There are 5 parts. Make sure you complete the parts in numerical order. Notice that part 4 occurs in the code after part 5. As stated in the part 5 comments, you should complete part 4 before part 5 because part 5 has a step that says: "// declare and instantiate an ActionListener" This ActionListener must be an object of the private inner button handler class that you write in part 4. The 5 parts of 12-2 each have helpful comments. The comments will guide you about what code to write. Button instantiation -------------------- Suppose you define a button as follows: JButton three; To instantiate it with its label set to "3 x 3", you would write: three = new JButton("3 x 3");
  • 8. Part 2 ------ Note that the Game class inherits from JPanel. Therefore, the panel you are asked to add to the center of the content pane is the "game" object. Part 4 button handler --------------------- You have to create a private inner class to handle events from any of the three game setup buttons. This course is cumulative. Each new chapter builds on previous chapters. Week 4 had a video called Java GUI Button Components. The code for that video was supplied in a folder in week 4. Here is a section of the code shown in that video: private class CommandHandler implements ActionListener { public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == btnDisplayTrees) { displayTrees(); return; } if (source == btnDisplayWater) { displayWater(); return; } if (source == btnPackWindow) { packWindow(); return; } if (source == btnReset) { reset();
  • 9. return; } } etc. The above code shows a private inner class named CommandHandler that handles button events. You can name your button handler whatever you want, such as ButtonHandler, but you must use the same name in part 5 after the comment: // declare and instantiate an ActionListener In the above video example, there is an if test for each button event. Each of the if blocks does something and then returns. In your button handler, you also have to do a certain thing for each button as specified in the comments. However, you cannot then simply return because validate() must be called at the end of the function--no matter which button was clicked. There are 2 simple ways to achieve this: 1) Use nested if/else's followed by the validate() call, or 2) Call validate() after each button's processing and then return from each one as in the video example. Part 4 setUpGame() ------------------ The part 4 comments include: // depending on which button was pressed, // call the setUpGame method of the Game class // with arguments 3, 4, or 5 // the API of that method is: // public void setUpGame(int nSides) To call a function we need an object of its class. Does our framework code have an object for us of type Game? Looking near the beginning of the NestedLayoutPractice class that we are in, you will see the following declaration: private Game game; So, game is an object reference of type Game that we can use. Your framework starting code already includes the following line of code in part 2: game = new Game(3); // instantiating the GamePanel object This is where the game object is actually created. It is passed a value of 3 in the constructor call. This will cause the game
  • 10. to be created with 3 rows by 3 columns of numbered squares. Now back to your part 4 handler comments. The comments say to change the game setup as instructed based on which button was clicked. If you look at the example user interface you will see that there are 3 buttons to change the game to 3 x 3, or 4 x 4, or 5 x 5 squares. You should have already declared these buttons in part 1 and created them in part 3 as instructed. In part 4, your event handler function must handle when each of the buttons is clicked. If, for exaample, the 4 x 4 button is clicked, then you should have the following line of code for that event: game.setUpGame(4); Don't overthink this. It is a simple function call using the game object, its setUpGame() method, and a literal parameter of 4. At the end of the function, call Solution NestedLayoutPractice.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class NestedLayoutPractice extends JFrame { private Container contents; private Game game; private BorderLayout bl; private JLabel bottom; private JPanel top; private JButton btnDisplayTrees; private JButton btnDisplayWater; private JButton btnPackWindow; // ***** Task 1: declare a JPanel named top // also declare three JButton instance variables // that will be added to the JPanel top // these buttons will determine the grid size of the game:
  • 11. // 3-by-3, 4-by-4, or 5-by-5 // Part 1 student code starts here: // Part 1 student code ends here. public NestedLayoutPractice(){ super("Practicing layout managers"); contents = getContentPane(); // ***** Task 2: // instantiate the BorderLayout manager bl bl = new BorderLayout(); // Part 2 student code starts here: // set the layout manager of the content pane contents to bl:------- bl.layoutContainer(contents); game = new Game(3); // instantiating the GamePanel object // add panel (game) to the center of the content pane contents.add(game); // Part 2 student code ends here. bottom = new JLabel("Have fun playing this Tile Puzzle game", SwingConstants.CENTER); // ***** Task 3: // instantiate the JPanel component named top top = new JPanel(); // Part 3 student code starts here: top.setLayout(new GridLayout(1, 3, 5, 5)); // set the layout of top to a 1-by-3 grid-------- // instantiate the JButtons that determine the grid size btnDisplayTrees = new JButton("3 x 3"); btnDisplayWater = new JButton("4 x 4"); btnPackWindow = new JButton("5 x 5"); // add the buttons to JPanel top top.add(btnDisplayTrees); top.add(btnDisplayWater); top.add(btnPackWindow); // add JPanel top to the content pane as its north component top.add(contents,BorderLayout.NORTH); // Part 3 student code ends here.
  • 12. // ***** Task 5: // Note: search for and complete Task 4 before performing this task // Part 5 student code starts here: // declare and instantiate an ActionListener CommandHandler ch = new CommandHandler(); // register the listener on the 3 buttons btnDisplayTrees.addActionListener(ch); btnDisplayWater.addActionListener(ch); btnPackWindow.addActionListener(ch); // that you declared in Task 1 // Part 5 student code ends here. contents.add(bottom, BorderLayout.SOUTH); setSize(325, 325); setVisible(true); } // ***** Task 4: // create a private inner class that implements ActionListener // your method should identify which of the 3 buttons // was the source of the event // depending on which button was pressed, // call the setUpGame method of the Game class // with arguments 3, 4, or 5 // the API of that method is: // public void setUpGame(int nSides) // At the end of the method call validate() // Part 4 student code starts here: // Part 4 student code ends here. private class CommandHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ Object source = e.getSource(); if (source == btnDisplayTrees){ //displayTrees(); game.setUpGame(3); game.validate(); return;
  • 13. } if (source == btnDisplayWater){ // displayWater(); game.setUpGame(4); game.validate(); return; } if (source == btnPackWindow){ //packWindow(); game.setUpGame(5); game.validate(); return; } // if (source == btnReset){ // reset(); // return; // } } } public static void main(String[] args){ NestedLayoutPractice nl = new NestedLayoutPractice(); nl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }