[英]Paint method gets called but doesn't redraw
The problem here is that the paintComponent() method gets called, it gets the necessary variables for fillRect() but doesn't actually draw anything after a key is pressed. 这里的问题是,paintComponent()方法被调用,它获取了fillRect()的必要变量,但是在按下某个键后实际上并未绘制任何内容。 I don't understand why since the returned value of mato.getPositionX() does get incremented every time the D key is pressed and the incremented value gets passed to fillRect().
我不明白为什么,因为每次按D键并将增加的值传递给fillRect()时,mato.getPositionX()的返回值都会增加。 Here's the code:
这是代码:
Screen class 屏幕类
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 class 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;
}
}
Mato class 马托班
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
}
The main cause of your problem is you are calling setVisible
to early... 问题的主要原因是您正在调用
setVisible
到早期...
The general rule of thumb is, call setVisible
only after you have prepared the UI 一般的经验法则是,仅在准备好UI后才调用
setVisible
public Screen() {
DrawScreen screen = new DrawScreen();
mDrawScreensMato = screen.getMato();
addKeyListener(this);
add(screen);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This is a useless call as DrawScreen
// does not provide appropriate sizing hints to the layout manager
pack();
setSize(400, 400);
// This needs to be called AFTER the size of window has been determined,
// as it uses the size of the window to determine it's location
setLocationRelativeTo(null);
setVisible(true);
}
KeyListener
is notoriously troublesome, you would better of using Key Bindings 众所周知,
KeyListener
很麻烦,您最好使用键绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.