I am studying Java via the Stanford open courses in addition to other books.
Currently I am working on an assignment called Breakout.
I understand the concept of addMouseListeners() and addKeyListeners to the canvas.
However, I am having trouble conceptually (and on code level) understanding how to invoke a method call on an existing object that I have created on the canvas. My main issue is conceptual -- why can I not change the state of an existing object using mouse and key listeners when I have declared the object as a private instance variable as well.
Here is the most basic code to explain where I am having trouble. (Please note that I have imported the JSwing library as well -- however I have not used it thus far in the Stanford course or other resources that I have been using. Hence, I do not have an understanding of it). Any and all help is appreciated.
/*
* File: Example.java
* Name: Jasjeet
*/
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example extends GraphicsProgram {
public void run() {
int width = getWidth(); // width of window in pixels
int height = getHeight(); // height of window in pixels
int x = (width/2) - 36; // x coordinates for GRect
int y = (height/2) - 36; // y coordinates for GRect
GRect outer = new GRect (x, y, 72, 72); //Adding a new GRect
add(outer);
outer.setColor(Color.red);
outer.setFillColor(Color.red);
outer.setFilled(true);
addKeyListeners(); // added Key Listeners to the canvas
addMouseListeners(); // added Mouse Listeners to the canvas
}
/* Trying to invoke a mouse click evnt below but it does not do anything to the GRect*/
public void mouseClicked(MouseEvent e) {
while (true) {
if (e.getX() > 0 && e.getY()<50) {
outer.move(1, 0);
pause(50);
}
else {
outer.move(-1, 0);
pause(50);
}
}
private GRect outer; // Declared the GRect outer as a private instance var
}