BCA Slip16 Java

Java

Slip16

Q.1) Write an application in Java using Awt to display 4 X 4 squares on the screen. One of the block will be active with black color. All other blocks should be filled with blue color. Provide command buttons as follows to move the active cell. The active cell should be changed only if it is within the boundary of the squares otherwise give the beep. [Marks 30] 

Solution

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assgn16 extends Frame implements ActionListener
{
  Button moveBtns[]=new Button[4];
  Button b1[] = new Button[16];
  String icons[]={"Left","Up","Right","Down"};
  int cnt=1;
  public Assgn16()
  {
      setLayout(new GridLayout(5,4));
      for(int i=0;i<16;i++)
      {
   b1[i] = new Button();
           add(b1[i]);
           b1[i].setBackground(Color.white);
      }
b1[0].setBackground(Color.black);

        for(int i=0;i<4;i++)
     {

    moveBtns[i]=new Button();
    add(moveBtns[i]);
    moveBtns[i].addActionListener(this);
    }
   moveBtns[0].setLabel("Left");
       moveBtns[1].setLabel("Up");
       moveBtns[2].setLabel("Right");
       moveBtns[3].setLabel("Down");
setSize(300,300);
setVisible(true);
setTitle("Grid Example");
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
public void actionPerformed(ActionEvent e)
{
Button btn=(Button) e.getSource();
b1[cnt-1].setBackground(Color.white);
if(e.getSource()==moveBtns[0])
{
if(cnt%4!=1)
cnt--;
}
if(btn==moveBtns[1])
{
if(cnt>4)
cnt=cnt-4;
}
if(btn==moveBtns[2])
  {
if(cnt%4!=0)
cnt++;
}
if(btn==moveBtns[3])
{
if(cnt<13)
cnt=cnt+4;
}
b1[cnt-1].setBackground(Color.black);
}


public static void main(String args[])
{
new Assgn16();
}
}

BCA Pratical Solution

My name is Vivek And I from Mumbai and Complete my Graduation Bca.my Age is 23 Years.

Post a Comment

Previous Post Next Post