user2951334
user2951334

Reputation: 1

My class inheriting JLabel won't show up but if I change the type to JLabel it does

Ok, so I made a class called Tile. This class extends JLabel.

public Tile()
{
    super();
}

Should behave the same as JLabel, no? but when I try to use it in my code, it does not show up in the correct position. If I do a call to the bounds of the Tile, it gives what I would expect, yet it is not AT that position. http://puu.sh/58eUg.jpg with the tile used, http://puu.sh/58eVT.png if I used JLabel in the places where Tile was called.

Container cPane = getContentPane();

    for(int x = 0;x<8;x++)
    {
        for(int y = 0;y<8;y++)
        {
            grid[x][y] = new Tile();
            grid[x][y].setBorder(BorderFactory.createLineBorder(Color.black));
            grid[x][y].setBounds(50*x,50*y,100,100);
            getContentPane().add(grid[x][y]);
            cPane.add(grid[x][y]);
        }
    }

Any help would be appreciated.

Upvotes: 0

Views: 118

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Aha, my comment to your question was right --

Let me guess: you've overridden the getX() and getY() methods without realizing that your methods were overrides, maybe? ...

You are in fact overriding getX() and getY(). These methods are key methods of JComponent that the layout managers and GUI use to set location of components. If overridden, your component's behavior on the GUI will be completely messed up.

This is one reason to avoid extending complex classes like components unless necessary. Favor composition over inheritance.

For instance you could create a little factory method to create your tile/JLabels, and you could back the component with a non-GUI model class that holds all the smarts of the GUI. An example of this would be something like Conway's Game of Life, where there exists a logical grid LifeSquares as well as a separate GUI that is little more than a "view" of the logical grid as well as has wiring to pass user interactions such as mouse presses to a "control" class.

Upvotes: 5

Related Questions