Hi, I'm sure this is a simple fix, but I don't know what to use to fix it. I am playing around with a program that allows the user to interact with an object. The program I'm starting allows the user to choose a direction, and move a square 5 pixels. However, I can't seem to get it to work. When you click on the "Up" button, the square is supposed to move 5 pixels up, and when you click on "Left," the square moves 5 pixels left, and so on...
Here is the code I created so far, and when I click on one of these buttons, the square doesn't do anything. I'm sure it's a simple fix, I just don't know what it is.
Any help is greatly appreciated. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class InteractionX {
static JFrame frame;
static Container contain;
static JButton up;
static JButton down;
static JButton left;
static JButton right;
static Panel controls;
static Panel canvasArea;
static int x = 75;
static int y = 75;
static class InteractXCanvas extends Canvas {
public void paint(Graphics g) {
g.fillRect(x,y,10,10);
}
}
static class InteractXMovement implements ActionListener {
InteractXCanvas IXC = new InteractXCanvas();
public void actionPerformed(ActionEvent ae) {
String whichButton;
whichButton = ae.getActionCommand();
int x2 = 0;
int y2 = 0;
if(whichButton.equals("Up")) {
y = y + 5;
}
if(whichButton.equals("Down")) {
y = y-5;
}
if(whichButton.equals("Left")) {
x = x-5;
}
if(whichButton.equals("Right")) {
x = x+5;
}
IXC.repaint();
}
}
public static void main(String[] args) {
InteractXCanvas IXC = new InteractXCanvas();
InteractXMovement IXM = new InteractXMovement();
frame = new JFrame("Interaction World");
contain = new Container();
up = new JButton("Up");
down = new JButton("Down");
left = new JButton("Left");
right = new JButton("Right");
controls = new Panel();
canvasArea = new Panel();
up.addActionListener(IXM);
down.addActionListener(IXM);
left.addActionListener(IXM);
right.addActionListener(IXM);
frame.setSize(500,500);
IXC.setSize(100,100);
contain = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contain.setLayout(new GridLayout(2,3));
controls.add(up);
controls.add(down);
controls.add(left);
controls.add(right);
canvasArea.add(IXC);
frame.setVisible(true);
}
}