Как добавить компоненты GraphI c из другого класса в JFrame? - PullRequest
0 голосов
/ 27 апреля 2020

Я делаю шахматную доску gui JFrame, у которой есть меню в северной части JFrame, фактическая шахматная доска в середине JFrame и JPanel статуса в нижней части приложения. У меня проблемы с отображением шахматной доски на JFrame. Существует класс шахматной фигуры (представляет один квадрат), класс шахматной доски (который объединяет все шахматные фигуры) и класс шахматной игры, который помещает шахматную доску в gui. Мне просто нужна помощь с отображением шахматной доски на JFrame прямо сейчас, и мне не нужна помощь с функциональностью. Мой класс Checkergame:

    frame.setSize(505, 585);
    frame.setLayout(new BorderLayout());


    JMenuBar menuBar= new JMenuBar();
    JMenu menuTwo = new JMenu("Game");
    JMenuItem newGame = new JMenuItem("New Game");
    JMenuItem exit = new JMenuItem("Exit");
    menuTwo.add(newGame);
    menuTwo.add(exit);
    menuBar.add(menuTwo);


    JMenu helpTwo = new JMenu("Help");
    JMenuItem rules = new JMenuItem("Checker Game Rules");
    JMenuItem about = new JMenuItem("About Checker Game App");
    helpTwo.add(rules);
    helpTwo.add(about);
    menuBar.add(helpTwo);
    frame.add(menuBar , BorderLayout.NORTH);

    JPanel game = new JPanel();
    CheckerBoard c = null;


    try {
        frame.getContentPane().add(new CheckerBoard(boardStatus));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    frame.add(game, BorderLayout.CENTER);

    JPanel status = new JPanel();
    status.setLayout(new GridLayout());
    JLabel statusTwo = new JLabel("12 Red : 12 Black");

    status.add(statusTwo);
    status.add(name);
    frame.add(statusTwo, BorderLayout.SOUTH);



    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

Мой класс шахматной доски:

public class CheckerBoard extends JPanel {
private char[][] boardStatus;

public CheckerBoard(char [][] boardStatus) throws Exception {
    JPanel board = new JPanel();

    board.setLayout(new GridLayout(8,8));


    for (int row = 0; row < 8; row++) {
        for (int column = 0; column < 8; column++) {
            board.add(new CheckerPiece(row, column, boardStatus[row][column]));
        }
    }

    board.setVisible(true);



}

Мой класс шахматной доски:

public class CheckerPiece extends JComponent{

    private int row;
    private int column;
    private char status;
    final int y1 = 60;
    final int x1 = 480;


    public CheckerPiece(int row, int column, char status) throws Exception {

        setRow(row);
        setColumn(column);
        setStatus(status);
    }

    public int getRow() {
        return row;
    }



    public void setRow(int row) throws Exception {
        if (row >= 0 && row <= 7) {
            this.row = row;
        } else throw new IllegalCheckerboardArgumentException("Row must be between 0 and 7");

    }



    public int getColumn() {
        return column;
    }



    public void setColumn(int column) throws Exception {
        if (column >= 0 && column <= 7) {
            this.column = column;
        } else throw new IllegalCheckerboardArgumentException("Column must be between 0 and 7");

    }



    public char getStatus() {
        return status;
    }



    public void setStatus(char status) throws Exception {
        if (status == 'b' || status == 'e' || status == 'r')
        this.status = status;
        else throw new IllegalCheckerboardArgumentException("Status must be 'b', 'e', or 'r'.");
    }

    public void paintComponents(Graphics g) {
        int x = 0;
        int y = 0;
        int count = 0;
        if (status == 'b' ) {
            g.setColor(Color.GREEN);
            g.fillRect(0 + x, 0 + y, 60, 60);
            g.setColor(Color.BLACK);
            g.fillOval(5+x, 5 + y, 40, 40);
            x += 60;
            count++;
        }
        if (status == 'e') {
        g.setColor(Color.WHITE);
        g.fillRect(0 + x,0 + y, 60, 60);
        x+= 60;
        count++;
        }
        if (status == 'r') {
            g.setColor(Color.GREEN);
            g.fillRect(0 + x,0 + y, 60, 60);
            g.setColor(Color.RED);
            g.fillOval(5 + x, 5 + y, 40, 40);
            x += 60;
            count++;
        }
        if (count % 8 == 0) {
            y += 60;
        }


    }


}

1 Ответ

0 голосов
/ 27 апреля 2020

Вам нужен метод в вашем классе CheckerBoard для возврата JPanel, чтобы его можно было добавить к JFrame.

import java.awt.GridLayout;

import javax.swing.JPanel;

public class CheckerBoard extends JPanel {
    private static final long serialVersionUID = 1L;

    private JPanel board;

    public CheckerBoard(char [][] boardStatus) 
            throws Exception {
        int height = boardStatus.length;
        int width = boardStatus[0].length;
        board = new JPanel();
        board.setLayout(new GridLayout(width, height));

        for (int row = 0; row < width; row++) {
            for (int column = 0; column < height; column++) {
                board.add(new CheckerPiece(row, column, 
                        boardStatus[row][column]));
            }
        }
    }

    public JPanel getPanel() {
        return board;
    }

}
...