I have searched few several questions with similar titles to this (for example how to use jpanel with paint (or repaint)) but I can't find a reason for my code not to work. I'm a graphics with JPanels newbie so my first attempt at this sort of thing is to make a triangle that one can move with the arrow keys. I got the triangle drawn fine, with no problems. However, when I tried to move the triangle with the arrows, it didn't move. Can anyone find why it won't repaint?
JPanel code (I also have a separate class for the JFrame itself which only makes the frame and adds the panel, if you need to see that tell me and I'll edit it in):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Drawpanel extends JPanel implements KeyListener{
int[] xcoords = {-20,0,20};//Triangle x coordinates
int[] ycoords = {20,-20,20};//Triangle y coordinates
int x = 100;//X coordinate for drawing the triangle
int y = 100;//Y coordinate for drawing the triangle
Graphics2D g2d;
Polygon tri = new Polygon(xcoords,ycoords,xcoords.length);//triangle
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2d = (Graphics2D)g;
g2d.translate(x,y);//draw triangle at x and y coordinates
g2d.setColor(new Color(234,22,72));
g2d.fill(tri);
}
public void keyTyped(KeyEvent k){}
public void keyReleased(KeyEvent k){}
public void keyPressed(KeyEvent k)
{
int keycode = k.getKeyCode();
switch(keycode)
{
case KeyEvent.VK_DOWN://if down arrow pressed, decrease ship y coordinate by 10
y -= 10;
case KeyEvent.VK_UP:
y += 10;
case KeyEvent.VK_LEFT:
x -= 10;
case KeyEvent.VK_RIGHT:
x += 10;
}
repaint();//screen doesn't repaint
}
}
Don't use a KeyListener. Swing was designed to be used with Key Bindings
.
The probable problem is that the panel doesn't have focus and doesn't respond to the KeyEvents. See Motion Using the Keyboard for more information and a solution using Key Bindings.
Another possible problem is that you don't override the getPreferredSize()
method of your panel to return an appropriate Dimension, so the size is 0 so Swing thinks there is nothing to paint.