Java
Slip16
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();
}
}
Tags:
java