How do I make my custom Swing component visible?

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2011-01-12T21:30:18Z Indexed on 2011/01/12 21:53 UTC
Read the original article Hit count: 191

Filed under:
|

I have no idea why it won't show. First I create an instance of the component and then add it to a certain element in a two-dimensional JPanel array. Then I loop through that array and add each JPanel to another JPanel container which is to hold all the JPanels.

I then add that final container to my JFrame window and set visibility to true, it should be visible?

public class View extends JFrame {

    Board      gameBoard;
    JFrame     gameWindow   = new JFrame("Chess");
    JPanel     gamePanel    = new JPanel();
    JPanel[][] squarePanel  = new JPanel[8][8];
    JMenuBar   gameMenu     = new JMenuBar();
    JButton    restartGame  = new JButton("Restart");
    JButton    pauseGame    = new JButton("Pause");
    JButton    log          = new JButton("Log");

    View(Board board){
        gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
        gameWindow.setSize(400, 420);
        gameWindow.getContentPane().add(gamePanel, BorderLayout.CENTER);
        gameWindow.getContentPane().add(gameMenu, BorderLayout.NORTH);
        gameMenu.add(restartGame);
        gameMenu.add(pauseGame);
        gameMenu.add(log);
        gameBoard = board;
        drawBoard(gameBoard);
        gameWindow.setResizable(false);
        gameWindow.setVisible(true);

    }

    public void drawBoard(Board board){
        for(int row = 0; row < 8; row++){
            for(int col = 0; col < 8; col++){
                Box box = new Box(board.getSquare(col, row).getColour(), col, row);
                squarePanel[col][row] = new JPanel();
                squarePanel[col][row].add(box);
            }
        }
        for(JPanel[] col : squarePanel){
            for(JPanel square : col){
                gamePanel.add(square);
            }
        }
    }
}

@SuppressWarnings("serial")
class Box extends JComponent{
    Color boxColour;
    int col, row;
    public Box(Color boxColour, int col, int row){
        this.boxColour = boxColour;
        this.col = col;
        this.row = row;
        repaint();
    }
    protected void paintComponent(Graphics drawBox){
        drawBox.setColor(boxColour);
        drawBox.drawRect(50*col, 50*row, 50, 50);
        drawBox.fillRect(50*col, 50*row, 50, 50);
    }
}

A final question as well. Notice how each Box component has a position, what happens to the position when I add the component to a JPanel and add the JPanel to my JFrame? Does it still have the same position in relation to the other Box components?

© Stack Overflow or respective owner

Related posts about java

Related posts about swing