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

不想你离开。 提交于 2021-01-29 12:18:38

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19761204/my-class-inheriting-jlabel-wont-show-up-but-if-i-change-the-type-to-jlabel-it-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!