0

I don't know why. At all.
Just that it won't repaint!
My code:

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class Frame extends JFrame implements KeyListener{
	JPanel content;
	int W = 200;
	int H = 200;
	public Frame(){
		setSize(700,250);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		content = new JPanel();
		setContentPane(content);
		content.paint(getGraphics());
		content.addKeyListener(this);
		setVisible(true);
	}
	@Override
	public void paint(Graphics g){
		g.clearRect(0, 0, getWidth(), getHeight());
		g.drawRect(0, 0, W, H);
		g.fillRect(0,0,W,H);
	}
	public static void main(String[] args){
		new Frame();
	}
	public void keyPressed(KeyEvent e) {
		int getKey = e.getKeyCode();
		if(getKey == KeyEvent.VK_RIGHT){
			W++;
		}else if(getKey == KeyEvent.VK_LEFT){
			W--;
		}
		if(getKey == KeyEvent.VK_UP){
			H--;
		}else if(getKey == KeyEvent.VK_DOWN){
			H++;
		}
		repaint();
	}
	public void keyReleased(KeyEvent e) {
		
	}
	public void keyTyped(KeyEvent e) {
		
	}
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by mangopearapples
0

Your panel doesn't have the focus, so it's not receiving your key events. Add

content.requestFocusInWindow();

after the setVisible() call.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.