【问题标题】:Update component position at run time在运行时更新组件位置
【发布时间】:2011-10-29 21:42:57
【问题描述】:

我目前遇到以下问题:

我需要在运行时动态更新组件定位。我正在为外部应用程序制作表单编辑器。我将包装类用于标准 Swing 组件,目前是 JPanelJLabel。面板使用 TableLayout。我将每个组件的位置存储在每个组件的字段中。当某些事情发生变化时,我需要递归更新所有位置。这是我更新职位的方法:

 public void updatePositioning() {
    Component[] comps = getComponents();
    removeAll();
    for (Component comp:comps) {
        System.out.println("Moving component "+comp + " to x="+pos.get(comp).getX() 
                +" to y="+pos.get(comp).getY());   
        c = new TableLayoutConstraints(String.valueOf(pos.get(comp).getX())+","
                +String.valueOf(pos.get(comp).getY()));

        add(comp, c);
        if (comp instanceof EditPanel) ((EditPanel)comp).updatePositioning();
    }
    repaint();
    revalidate(); 
}

我知道,这很粗糙,但它不起作用。所有组件似乎都属于 0,0 网格单元。正如我通过调试器看到的那样,X 和 Y 是正确的。以下是我向面板添加组件的方法:

public void addComponent(TableLayouted comp, int x, int y) {
    c = new TableLayoutConstraints(String.valueOf(x)+","+String.valueOf(y));
    add((JComponent) comp, c);
    //saving position of the component
    pos.put((Component) comp, comp.getTablePositon());
    System.out.println("Component "+comp+"added to x="+x+"y="+y);
}

有什么建议吗?

【问题讨论】:

  • 怀疑它会有所作为,但为了将来的参考,它应该是 revalidate(),然后是 repaint()。顺序可能很重要。

标签: java swing jpanel tablelayout updating


【解决方案1】:

【讨论】:

  • 请问,我应该在哪里插入这段代码。我已经在我的 repaint(); 之前插入了它。 revalidate();,它不会改变任何东西。 :(
  • 进入你的源代码。如需更具体的答案,请添加SSCCE
【解决方案2】:

我终于用下面的代码解决了:

Component[] comps = getComponents();
removeAll();
layout = new TableLayout();
layout.setColumn(columns);
layout.setRow(rows);
setLayout(layout);

这意味着,完全重新创建所有布局是有效的。感谢大家的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2017-07-31
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多