gpt4 book ai didi

java - 我不知道为什么我的主类没有从我的 Gameplay 类获取数据

转载 作者:行者123 更新时间:2023-11-30 05:35:00 26 4
gpt4 key购买 nike

我非常确定,我的 Main 类中的这么多代码应该能够显示黑色背景以及我在 Gameplay 类中写下和描述的其他内容,但事实并非如此。 t。

我的类:

package brickbraker;

public class Main extends Gameplay {

public static void main(String[] args) {
JFrame obj = new JFrame();
Gameplay gamePlay = new Gameplay();
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Brick Breaker");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
}

}

这是我的第二堂课:

package brickbraker;

public class Gameplay extends JPanel implements KeyListener, ActionListener {
private int playerX = 310;
private int ballPosX = 120;
private int ballPosY = 350;
private int ballXdir = -1;
private int ballYdir = -2;

public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}

public void paint(Graphics g) {
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);

// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);

// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);

// the ball
g.setColor(Color.yellow);
g.fillRect(ballPosX, ballPosY, 20, 20);
}
}

最佳答案

首先,当你向可见容器添加组件时,你必须调用 repaintrevalidate方法。那么obj.add(gamePlay);之后做obj.repaint();obj.revalidate(); 。就您而言,您可以轻松 obj.add(gamePlay);然后obj.setVisible(true);为了避免使用 repaintrevalidate .

其次,在 Gameplay同学们,你们@Override paint方法而不是 paintComponent方法。应该是:

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //Always call super when overriding paint component
//Custom painting
}

最后,Swing 应用程序应该在自己的名为 EDT(事件调度线程)的线程中运行。使用SwingUtilities#invokeLater为了做到这一点。类似于:

SwingUtilities.invokeLater(() -> {
JFrame obj = new JFrame();
Gameplay gamePlay = new Gameplay();
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Brick Breaker");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
});

关于java - 我不知道为什么我的主类没有从我的 Gameplay 类获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826783/

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