gpt4 book ai didi

java - Paint 方法被调用但不重绘

转载 作者:行者123 更新时间:2023-12-01 13:17:16 25 4
gpt4 key购买 nike

这里的问题是调用了paintComponent()方法,它获取了fillRect()所需的变量,但在按下按键后实际上并没有绘制任何东西。我不明白为什么,因为每次按下 D 键时 mato.getPositionX() 的返回值都会增加,并且增加的值会传递给 fillRect() 。代码如下:

屏幕类别

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...

一般经验法则是,仅在准备好 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 是出了名的麻烦,你最好使用 Key Bindings

关于java - Paint 方法被调用但不重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com