获取任何类型swing对象宽度的Java方法?

获取任何类型swing对象宽度的Java方法?,java,swing,class,methods,Java,Swing,Class,Methods,我有这个方法来放置摆动中的对象。此时,它只支持按钮(或具有已定义方法的任何其他对象)。我需要一个可以用于任何对象的方法,而不必为每种类型的对象(按钮、文本区域、面板等)定义一个方法 这是我的密码: // Visual Methods for placing visual objects::: static class Layout{ static class Button{ // buttons static void PlaceUnder(JButton

我有这个方法来放置摆动中的对象。此时,它只支持按钮(或具有已定义方法的任何其他对象)。我需要一个可以用于任何对象的方法,而不必为每种类型的对象(按钮、文本区域、面板等)定义一个方法

这是我的密码:

    // Visual Methods for placing visual objects:::
static class Layout{
    static class Button{ // buttons
            static void PlaceUnder(JButton target,JButton src){
                int x = src.getLocation().x;
                int y = src.getLocation().y + src.getSize().height+2;
                target.setLocation(x,y);
            }
    static void PlaceOver(JButton target,JButton src){
        int x = src.getLocation().x;
        int y = src.getLocation().y - target.getSize().height-2;
        target.setLocation(x,y);
        }
    } // end of buttons
}
    // done....

使用
javax.swing.JComponent
(或
java.awt.Component
)基类。每个Swing组件都从这些组件扩展而来

static void placeUnder(JComponent target, JComponent src) {
    int x = src.getLocation().x;
    int y = src.getLocation().y + src.getSize().height+2;
    target.setLocation(x,y);
}

你为什么要重新发明轮子?Swing已经有很多布局管理器。除非你真的,真的知道自己在做什么,否则你不应该尝试自己实现一个。如果您知道,只需阅读组件中声明的javadoc thet getSize(),您就会知道所有Swing组件都扩展了。查看
JButton
的JavaDocs,看看它是如何扩展的。您应该为所有UI找到一个共同的祖先components@JB是的,我知道我在重新发明轮子,但这只是为了学习。。。不管怎么说,我喜欢对蜜蜂的完全控制,因为它能够将物体精确地放置在我想要的地方。