Добавление JButton в класс, расширенный JPanel, не отображает кнопку - PullRequest
0 голосов
/ 30 декабря 2018

Когда я использую обычный JPanel, инициализированный внутри main вместо расширенного класса.Кнопка добавляется на панель без проблем и после запуска отображается в центре кадра (макет по умолчанию).

Я хотел бы иметь возможность добавлять кнопки в расширенный класс.Эта проблема возникает и в классе Screen, где мне нужна кнопка Play Again или кнопка Next Level.Экран также расширен классом JPanel, и JButtons инициализируются также внутри конструктора.

Я не уверен, что неправильная часть связана с добавлением компонентов или написанием кода для JPanel.

Вот код:

Main:

public static void main(String[] args) {

    //  window  -   class JFrame
    theFrame = new JFrame("Brick Breaker");

    // game panel initialization
    GamePanel gamePanel = new GamePanel(1);
    theFrame.getContentPane().add(gamePanel);

    //  base settings
    theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    theFrame.setLocationRelativeTo(null);
    theFrame.setResizable(false);
    theFrame.setSize(WIDTH, HEIGHT);
    theFrame.setVisible(true);
}

GamePanel Класс:

public class GamePanel extends JPanel {

// Fields
boolean running;
boolean clicked = false;
private int rows = 8, colms = 11, N = rows * colms, level;       // numbers of rows and columns
private int colmsC, rowsC;

private BufferedImage image;
private Graphics2D g;
private MyMouseMotionListener theMouseListener;
private MouseListener mouseListener;
private int counter = 0;

// entities
Ball theBall;
Paddle thePaddle;
Bricle[] theBricks;
Screen finalScreen;

public GamePanel(int level) {

    //  buttons
    JButton pause = new JButton(" P ");
    add(pause);

    this.level = level;
    init(level);

}
public void init(int level) {

    // level logic
    this.rowsC = level + rows;
    this.colmsC = level + colms;
    int count = rowsC * colmsC;

    thePaddle = new Paddle();
    theBall = new Ball();
    theBall.setY(thePaddle.YPOS - thePaddle.getHeight() + 2);
    theBall.setX(thePaddle.getX() + thePaddle.getWidth() / 2 - 5);
    theBricks = new Bricle[count];

    theMouseListener = new MyMouseMotionListener();
    addMouseMotionListener(theMouseListener);
    mouseListener = new MyMouseListener();
    addMouseListener(mouseListener);

    //  make a canvas
    image = new BufferedImage(BBMain.WIDTH, BBMain.HEIGHT, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    //  specific Bricks initialized
    int k = 0;
    for (int row = 0; row < rowsC; row++) {
        for (int col = 0; col < colmsC; col++) {
            theBricks[k] = new Bricle(row, col);
            k++;
        }
    }
    running = true;
}

public void playGame() {

    while (running) {
        //update
        if (clicked) {
            update();
        }
        // draw
        draw();

        // display
        repaint();

        //  sleep
        try {
            Thread.sleep(20);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//  update loop ( like playGame )
public void update() {

    // ball moving
    checkCollisions();
    theBall.update();

}
public void draw() {

    // background
    g.setColor(Color.WHITE);
    g.fillRect(0,0, BBMain.WIDTH, BBMain.HEIGHT-20);

    // the bricks
    int k = 0;
    for (int row = 0; row < rowsC; row++) {
        for (int col = 0; col < colmsC; col++) {
            theBricks[k].draw(g, row, col);
            k++;
        }
    }
    // the ball and the paddle
    theBall.draw(g);
    thePaddle.draw(g);

    //  counter
    String countString = new Integer(this.counter).toString();
    g.drawString(countString, 20, 20);

    // WIN / LOOSE SCREEN
    if (this.counter == this.N * 20) {
        win();
    }
    if (theBall.getRect().getY() + theBall.getRect().getHeight() >= BBMain.HEIGHT) {
        loose();
    }

}
public void paintComponent(Graphics g) {

    // retype
    Graphics2D g2 = (Graphics2D) g;

    // draw image
    g2.drawImage(image, 0, 0, BBMain.WIDTH, BBMain.HEIGHT, null);

    // dispose
    g2.dispose();
}

public void pause() {

    this.running = false;
    finalScreen = new Screen(this.level, counter);
    finalScreen.draw(g,"GAME PAUSED");
}

public void win() {

    this.running = false;
    finalScreen = new Screen(this.level, counter);
    finalScreen.draw(g,"YOU WIN");
}
public void loose () {

    this.running = false;
    finalScreen = new Screen(this.level, counter);
    finalScreen.draw(g,"YOU LOOSE");
}
public void addScore() {

    this.counter += 20;
    theBall.setDY(theBall.getDY() - 0.001);
}

//  Mouse Listeners
private class MyMouseListener implements MouseListener {
    @Override
    public void mouseClicked(MouseEvent e) {
        clicked = true;
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
private class MyMouseMotionListener implements MouseMotionListener {

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        if (clicked)
        thePaddle.mouseMoved(e.getX());

    }
}

}
...