我不知道为什么我的主班不从我的游戏课上获取数据

时间:2019-06-30 17:36:51

标签: java swing

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

我的Main班:

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);
    }
}

1 个答案:

答案 0 :(得分:1)

首先,将组件添加到可见容器时,必须调用Project.all - Project.includes(:project_images).where(project_images: { selected: true }) repaint方法。因此,在revalidate之后执行obj.add(gamePlay);obj.repaint();。就您而言,您可以轻松先obj.revalidate();,然后再obj.add(gamePlay);,以避免使用obj.setVisible(true);repaint

第二,在revalidate类中,您使用Gameplay @Override方法而不是paint方法。应该是:

paintComponent

最后,Swing应用程序应在自己的名为EDT(事件分发线程)的线程中运行。使用@Override protected void paintComponent(Graphics g) { super.paintComponent(g); //Always call super when overriding paint component //Custom painting } 来做到这一点。像这样:

SwingUtilities#invokeLater