0
여기에서 paintComponent() 메서드가 호출되면 fillRect()에 필요한 변수를 가져 오지만 실제로는 키를 누른 후에 아무 것도 그리지 않는 것이 문제입니다. 나는 mato.getPositionX()의 반환 값이 D 키를 누를 때마다 증가하고 증가 된 값이 fillRect()에 전달되기 때문에 왜 그런지 이해하지 못한다. 여기에 코드입니다 :Paint 메서드가 호출되었지만 다시 그려지지 않습니다.
Screen 클래스
public class Screen extends JFrame implements KeyListener {
private Mato mDrawScreensMato;
public Screen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setLocationRelativeTo(null);
setSize(400, 400);
DrawScreen screen = new DrawScreen();
mDrawScreensMato = screen.getMato();
addKeyListener(this);
add(screen);
}
//keyTyped
@Override
public void keyPressed(KeyEvent ke) {
int c = ke.getKeyCode();
if (c == KeyEvent.VK_D) {
mDrawScreensMato.setPositionX(mDrawScreensMato.getPositionX() + 1);
repaint();
}
}
//keyReleased
}
DrawScreen 클래스
public class DrawScreen extends JPanel {
private Mato mato;
public DrawScreen() {
mato = new Mato();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
System.out.println(mato.getPositionX());
g2d.fillRect(
mato.getPositionX(), mato.getPositionY(),
mato.MATO_WIDTH, mato.MATO_HEIGHT
);
}
public Mato getMato() {
return mato;
}
}
마토 클래스
public class Mato {
final int MATO_WIDTH = 20;
final int MATO_HEIGHT = 20;
final int MATO_START_POS_X = 20;
final int MATO_START_POS_Y = 40;
private int positionX;
private int positionY;
public Mato(){
positionX = MATO_START_POS_X;
positionY = MATO_START_POS_Y;
}
public void setPositionX(int positionX) {
this.positionX = positionX;
}
public int getPositionX() {
return positionX;
}
//Get/Set positionY
}
를 사용하여 게시 된 코드가 일부 컴파일 문제 후 확인을 작동하는 것 같다 것,
setVisible
를 호출한다 누락/주석 처리 된 메소드로 인해 해결되었습니다. 문제를 보여주는 [전체 예제] (http://stackoverflow.com/help/mcve)를 게시 해보십시오. 또한 키 수신기를 사용하지 않고 키 바인딩을 사용하십시오. 자세한 내용은 [키 바인딩 사용 방법] (http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)을 참조하십시오. – tenorsax