Question: JAVA PROGRAMMING HELP I have created a program called Run Kitty Run where I have made a interactive GUI but I need help adding functionality
JAVA PROGRAMMING HELP
I have created a program called Run Kitty Run where I have made a interactive GUI but I need help adding functionality to the Jbuttons. I need the buttons to move the ("=^.^=") string up down left or right across the board everytime the button is pressed. I think my error is in the ActionPerformed class. HERE IS MY SOURCE CODE BELOW please copy and paste it and see that I need to fix
import java.awt.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CheckerBoard extends JFrame implements ActionListener{
private final int ROWS = 8;
private final int COLS = 8;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private JPanel pane = new JPanel(new GridLayout(ROWS,COLS,GAP,GAP));
private JPanel[][] panel = new JPanel[ROWS][COLS];
private JLabel cat = new JLabel("=^.^=");
private JButton up = new JButton("UP");
private JButton down = new JButton("down");
private JButton left = new JButton("LEFT");
private JButton right = new JButton("RIGHT");
private Color color1 = Color.WHITE;
private Color color2 = Color.BLUE;
private Color tempColor;
public CheckerBoard() {
super ("Run Kitty Run");
int row = 4;
int col = 4;
add(pane);
add(up,BorderLayout.NORTH);
add(down,BorderLayout.SOUTH);
add(left,BorderLayout.WEST);
add(right,BorderLayout.EAST);
for (int x = 0; x < ROWS; ++x)
{
for(int y = 1; y < ROWS; ++y)
{
panel[x][y] = new JPanel();
pane.add(panel[x][y]);
if(x % ROWS == 0 && y % ROWS ==1)
{
tempColor = color1;
color1 = color2;
color2 = tempColor;
}
if(x % 2 == 0 && y % 2 == 1 || x % 2 == 1 && y % 2 == 0)
{
panel[x][y].setBackground(color1);
}
else {
panel[x][y].setBackground(color2);
}
panel[row][col].add(cat);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
int row = 4;
int col = 4;
if(source == up) {
++row;
panel[row][col].add(cat);
}
if(source == down) {
--row;
panel[row][col].add(cat);
}
if(source == left) {
--col;
panel[row][col].add(cat);
}
if(source == right) {
++col;
panel[row][col].add(cat);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CheckerBoard frame = new CheckerBoard();
frame.setSize(300,300);
frame.setVisible(true);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
