I am trying to make a rectangle move with arrow keys (for a game) but I am getting an error message. It says this, but it still doesnt work when I change it. I have tried multiple times but still receive the same error. Does anyone know why this error is appearing?
this is the error:
java.lang.Error: Do not use javax.swing.JFrame.add() use javax.swing.JFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Tutorial.main(Tutorial.java:109)
Here is my code:
// The "Test" class.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Tutorial extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer (5,this);
int x = 0, y = 0, velX = 0, velY = 0;
public Tutorial ()
{
tm.start();
addKeyListener(this);
setFocusable (true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent (Graphics g)
{
super.paintComponent (g);
g.setColor (Color.RED);
g.fillRect (x, y, 50, 30);
}
public void actionPerformed (ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
else if (x > 530)
{
velX = 0;
x = 530;
}
if (y < 0)
{
velY = 0;
y = 0;
}
else if (y > 330)
{
velY = 0;
y = 330;
}
x = x + velX;
y = y + velY;
repaint ();
}
public void keyPressed (KeyEvent e)
{
int c = e.getKeyCode ();
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1;
}
}
public void keyTyped (KeyEvent e) {}
public void keyReleased (KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main (String arge [])
{
Tutorial t = new Tutorial ();
JFrame jf = new JFrame ();
jf.setTitle ("Tutorial");
jf.setSize (600, 400);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
} // Test class
Related
If you move the shape over a little by pressing an arrow (release arrow key)and then press space bar it does like a diamond shape.
I want to be able to press the space-bar and then my shape draws a circle, instead of being able to go just Left
or Just Right
Can I code it do to Left and Down? To take two keyInputs?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Tutorial extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this);
int x = 250, y = 250, velX = 0, velY = 0;
public Tutorial()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 50,50);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0)
{
velX =0;
x = 0;
}
if (x > 450 )
{
velX = 0;
x = 450;
}
if (y < 0)
{
velY = 0;
y = 0;
}
if (y > 450)
{
velY = 0;
y = 450;
}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e)
{
float speed = .3f;
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT)
{
velX = -1; //LEFT
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1; //UP
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1; //RIGHT
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1; //DOWN
}
if (c == KeyEvent.VK_SPACE) {
if (y < 175) {
velX = 1; //RIGHT
}
if (c == KeyEvent.VK_SPACE) {
if (x > 275) {
velY = 1; //DOWN
}
}
if (c == KeyEvent.VK_SPACE) {
if (y > 275) {
velX = -1; //LEFT
}
}
if (c == KeyEvent.VK_SPACE) {
if (x < 175) {
velY = -1; //UP
}
}
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
Tutorial t = new Tutorial();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(500,500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
I am trying to move a rectangle while the key is pressed and to stop it on release like the game "Snake". As reference I followed this tutorial.
I tried to adjust a few things in my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class f3 extends JPanel implements ActionListener, KeyListener {
static JFrame frame;
static Timer t;
static int x, y, velx, vely, c;
f3(){
t = new Timer(5, this);
x = 0;
y = 0;
velx = 0;
vely = 0;
frame = new JFrame();
frame.addKeyListener(this);
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(false);
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 30);
t.start();
}
public void actionPerformed(ActionEvent e) {
x = x + velx;
y = y + vely;
repaint();
}
public void keyPressed(KeyEvent e) {
c = e.getKeyCode();
if(c == KeyEvent.VK_RIGHT) {
velx = 1;
vely = 0;
}
if(c == KeyEvent.VK_LEFT) {
velx = -1;
vely = 0;
}
if(c == KeyEvent.VK_UP) {
velx = 0;
vely = -1;
}
if(c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 1;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String args[]) {
new f3();
}
}
The value of velx and vely are set after a key event is triggered. Since you are using a Timer here, the GUI will continuously update because actionPerformed is repeatedly triggered.
Remove the Timer, then put the change section of keyPressed to this form and you will get a desired result.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
velx = 1;
vely = 0;
x = x + velx;
y = y + vely;
repaint();
}
}
Since velx and vely indicate the velocity of the movement (as opposed to moving the player one space at a time, for instance), you will want to also ensure keyReleased returns the appropriate velocity to 0 when the specific key associated with that axis is released.
You do not have a handler for keyReleased method, where you should set velocities to zero as such:
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
I should be able to move the rectangle with the arrow keys but after running the program a few times the rectangle does not move. To make the rectangle move I close Netbeans and reopen it. Then the rectangle is able to move but it stops moving after a couple tries. I want to solve this problem so I can make changes.
package project;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
//KeyListener is use with keyboard
public class main extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this); //for animation
int x = 50, y = 50, velX =0, velY = 0;
public main()
{
tm.start(); //starts timer
addKeyListener(this); //this refearing to KeyListener
setFocusable(true); //enable KeyListener
setFocusTraversalKeysEnabled(false); //shift or tab is not use so F
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,y,50,50);
}
public void actionPerformed(ActionEvent e)
{
if (x<0)
{
velX = 0;
x = 0;
}
if (x>500)
{
velX = 0;
x = 500;
}
if (y<0)
{
velY = 0;
y=0;
}
if (y>300)
{
velY = 0;
y = 300;
}
x = x + velX;
y = y + velY;
repaint(); // repaint rectangle
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode(); //get key
if (c == KeyEvent.VK_LEFT) // VK_Left is left arrow
{
velX = -3;
velY = 0;
}
if (c == KeyEvent.VK_UP) // VK_UP is up arrow
{
velX = 0;
velY = -3; // means up
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 3;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 3;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) //when you stop pressing
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
main m = new main();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(m);
}
}
This question already has an answer here:
Move a BALL on Jpanel with keyboard down key
(1 answer)
Closed 6 years ago.
I tried to create a ball that moves when I click the arrow buttons. When I click the arrow buttons, though, the ball does not respond. I tried to create a ball that moves when I click the arrow buttons. When I click the arrow buttons, though, the ball does not respond. Here's my code:
package ball.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Ball extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0;
int y = 0;
int velX;
int velY;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval(x, y, 20, 20);
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) {
x = 0;
}
if (x > 580) {
x = 580;
}
if (y < 0) {
y = 0;
}
if (y > 580) {
y = 580;
}
x += velX;
x += velY;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
velY = -1;
}
if (code == KeyEvent.VK_DOWN) {
velY = 1;
}
if (code == KeyEvent.VK_RIGHT) {
velX = 1;
}
if (code == KeyEvent.VK_LEFT) {
velX = -1;
}
}
#Override
public void keyReleased(KeyEvent e) {
velX = 0;
velY = 0;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
What is wrong with my code?
The answer is to use Key Bindings instead of KeyListener
So i have created an extended version of JPanel and unfortunately it doesn't respond to any key typing. Could you tell me what the problem is? I searched all the others posts but i couldn't find my error.
public class MyPanel extends JPanel implements ActionListener,KeyListener{
Timer tm=new Timer(5,this);
int x=0,y=0 ,velX=0, velY=0;
public MyPanel(){
tm.start();
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.RED);
g.fillRect(x,30,50,30);
}
public void actionPerformed(ActionEvent e){
if(x<0||x>370)
velX=-velX;
if(y<0||y>370)
velY=-velY;
y=y+velY;
x=x+velX;
repaint();
}
public void keyPressed(KeyEvent e){
int c=e.getKeyCode();
System.out.println("Cascsadas");
if(c==KeyEvent.VK_LEFT){
velX=-1;
velY=0;
}
if(c==KeyEvent.VK_UP){
velX=0;
velY=-1;
}
if(c==KeyEvent.VK_RIGHT){
velX=1;
velY=0;
}
if(c==KeyEvent.VK_DOWN){
velX=0;
velY=1;
}
}
public void keyTyped(KeyEvent e){};
public void keyReleased(KeyEvent e){};
}
And the class where i am using this JPanel is:
public class Tester
{
public static void main(String[] args){
MyPanel t=new MyPanel();
JFrame jf=new JFrame();
jf.setTitle("Tutorial");
jf.setVisible(true);
jf.setSize(600,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(t,BorderLayout.CENTER);
}
}
Your code doesn't work because your panel doesn't have focus.
The requestFocusInWindow() method only works when the panel is displayed on GUI is visible. Invoking the method in the constructor has no effect (and is not needed).
However, the real problem is that you add the panel to the frame AFTER the frame is visible. Your code should be something like:
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(t,BorderLayout.CENTER);
jf.setSize(600,400);
jf.setVisible(true);
The key is adding the panel to the content pane before the frame is made visible. It also doesn't make sense to make the frame visible and then change its size, so I always make the frame visiable as the last statement.
I searched all the others posts but i couldn't find my error
I find that hard to believe. This question is asked daily and we always recommend to use Key Bindings, so why are you still trying to use a KeyListener?
Swing was designed to be used with Key Bindings. See Motion Using the Keyboard for more information and an approach that does use Key Bindings.
I have posted an answer in the same context here
Diagonal movement of a simple sprite (up-down-left-right movement already done).
This post about KeyListener will help you to understand it more.
Here is the sample code to start:
(moving in all the direction left,right,top,bottom and diagonally also)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Apple extends JPanel implements ActionListener, KeyListener {
Timer timer = new Timer(5, this); // this refers to actionListener
int x = 0, velx = 0;
int y = 0, vely = 0;
public Apple() {
timer.start();
addKeyListener(this); // this refers to keylistener
setFocusable(true);
setFocusTraversalKeysEnabled(false); // because we are not using the shift or ctrl key
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// outer rectangle
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
}
public static void main(String[] args) {
Apple apple = new Apple();
apple.setSize(500, 500);
JFrame frame = new JFrame();
frame.add(apple);
frame.setLayout(null);
frame.setTitle("The Game");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
// animates rectangle
public void actionPerformed(ActionEvent arg0) {
if (x < 0) {
velx = 0;
x = 0;
}
if (x > 450) {
velx = 0;
x = 450;
}
if (y < 0) {
vely = 0;
y = 0;
}
if (y > 450) {
vely = 0;
y = 450;
}
x = x + velx;
y = y + vely;
repaint();
}
// Set of currently pressed keys
private final Set<Integer> pressed = new TreeSet<Integer>();
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(KeyEvent.VK_LEFT + "-" + KeyEvent.VK_RIGHT + "-" + KeyEvent.VK_UP + "-"
+ KeyEvent.VK_DOWN);
int c = arg0.getKeyCode();
pressed.add(c);
if (pressed.size() > 1) {
Integer[] array = pressed.toArray(new Integer[] {});
if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_UP) {
velx = -4;
vely = -4;
} else if (array[0] == KeyEvent.VK_UP && array[1] == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 4;
} else if (array[0] == KeyEvent.VK_RIGHT && array[1] == KeyEvent.VK_DOWN) {
velx = 4;
vely = -4;
} else if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_DOWN) {
velx = -4;
vely = 4;
}
} else {
if (c == KeyEvent.VK_LEFT) {
velx = -4;
vely = 0;
} else if (c == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 0;
} else if (c == KeyEvent.VK_UP) {
velx = 0;
vely = -4;
} else if (c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 4;
}
}
}
#Override
public void keyReleased(KeyEvent arg0) {
velx = 0;
vely = 0;
pressed.remove(Integer.valueOf(arg0.getKeyCode()));
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}