I am working if application and I cannot figure out how to make a box move forward one at a time when the spacebar is pressed. Here are my codes:
package DrawingInApplications;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import javax.swing.JFrame;
public class Program extends Drawing implements KeyListener{
Drawing d;
public Program (){
JFrame frame = new JFrame ("Program.java");
frame.setSize (300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible (true);
d = new Drawing(); // goes to class called Drawing and to call you add d
frame.add(d); // adds drawing class
d.Drawing(); // calls drawing METHOD!!! in drawing class (sry I put the same name lol)
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program p = new Program ();
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
int key = arg0.getKeyCode();
if (key == KeyEvent.VK_SPACE){
move += 1;
d.Drawing();
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
and
package DrawingInApplications;
import javax.swing.*;
import java.awt.*;
public class Drawing extends JPanel{
int move = 10;
public void Drawing (){
repaint(); // calls paint method because you cannot call it directly from Program class
}
public void paintComponent (Graphics g){
super.paintComponent(g); // a line that idk what it does, but you need to have it
g.fillRect(move, 10, 10, 10); // you know what this is
}
}
I am having trouble communicating through the different classes. When the spacebar (key event) is pressed then move += 1; and repaint();
I know how to do that. like I mentioned I believe it's the communicating between the classes.
Thanks for any help.