简体   繁体   English

我的继承JLabel的类不会显示,但是如果我将类型更改为JLabel,它将显示

[英]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. 好的,所以我开设了一个名为Tile的课程。 This class extends JLabel. 此类扩展了JLabel。

public Tile()
{
    super();
}

Should behave the same as JLabel, no? 应该和JLabel一样,不是吗? 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. 如果我调用Tile的边界,它会提供我期望的结果,但它不在该位置。 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. http://puu.sh/58eUg.jpg和使用的图块,如果我在调用Tile的地方使用了JLabel,则使用http://puu.sh/58eVT.png

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. 任何帮助,将不胜感激。

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? 让我猜测:您已经重写了getX()和getY()方法,却没有意识到您的方法是重写方法,也许吗? ... ...

You are in fact overriding getX() and getY() . 实际上,您正在重写getX()getY() These methods are key methods of JComponent that the layout managers and GUI use to set location of components. 这些方法是布局管理器和GUI用于设置组件位置的JComponent的关键方法。 If overridden, your component's behavior on the GUI will be completely messed up. 如果被覆盖,您的组件在GUI上的行为将被完全弄乱。

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. 例如,您可以创建一个小的工厂方法来创建tile / JLabel,并且可以使用包含GUI所有智能的非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. 例如,Conway的《生活游戏》,其中存在一个逻辑网格LifeSquares以及一个单独的GUI,它仅是逻辑网格的“视图”,并且具有传递用户交互之类的连线,例如鼠标按下一个“控件”类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM