java programming language .. Using Swing libraries. 4. Checkers: This exercise i
ID: 3724214 • Letter: J
Question
java programming language .. Using Swing libraries.
4. Checkers: This exercise is a slightly modified version of Exercise 4.14 from Roberts. Create a program to: Create a background rectangle so it fills the graphics window in the smaller dimension i.e. select the smaller of width and height of the window for the size of the blocks (making the checkerboard square), then center the checkerboard in the larger dimension Alternate between two colors (e.g. red and black), on an 8 by 8 board. You may choose other colors if you wish, as long as they are different and the checkers show up. Display checkers in the first three and last three rows in alternating colors, as illustrated in the textbook. Again, you may choose your own colors, as long as the checkers display correctly. Make your checkers centered in their square, and 80% of the square size. It may be helpful to notice the checkers always begin on black squares, in the first three and last three rows of the board.Explanation / Answer
I have written down the java program for the solution. I have given comments for some important notes in the program so that you can understand it. I have also shortened the program by creating object arrays.
File name : Checkers.java
import java.awt.*; //To import all the classes inside awt package
import javax.swing.*; //To import all the classes inside swing package
class Checker //Class name same as file name
{
Checker() //Constructor of the class
{
JFrame f = new JFrame();
f.setSize(1366,768); //Size of the frame
//f.setUndecorated(true); //You can use it to remove bar of the frame
f.setBackground(Color.white);
f.setLayout(null);
f.setVisible(true); //Visibility of the components of the frame
int i=1,j,s=8,w,h=0;//Variable i for counting row, s for total number of columns,w for width & h for height of the box
Label l[] = new Label[100]; //Object array for the class Label
for(j=0;j<8;j++) //For 8 rows
{
w=299;
for(;i<=s;i++) //For columns , variable i already initialised
{
if(j%2==0) //Condition check for coloring of the boxes(Label)
{
if(i%2==0)
{
l[i] = new Label();
l[i].setBackground(Color.black);
l[i].setBounds(w,h,96,96);
}
else
{
l[i] = new Label();
l[i].setBackground(Color.red);
l[i].setBounds(w,h,96,96);
}
w=w+96;
}
else
{
if(i%2==0)
{
l[i] = new Label();
l[i].setBackground(Color.red);
l[i].setBounds(w,h,96,96);
}
else
{
l[i] = new Label();
l[i].setBackground(Color.black);
l[i].setBounds(w,h,96,96);
}
w=w+96;
}
}
h=h+96;
s=s+8;
}
for(i=1;i<=64;i++)
f.add(l[i]);
}
public static void main(String a[])
{
ChessBoard ob = new ChessBoard();
}
}
Hope you got your solution. For any queries you can post it in the portal.
Thankyou.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.