在运行时更新组件位置
我目前遇到以下问题:
我需要在运行时动态更新组件定位。我正在为外部应用程序制作一个表单编辑器。我对标准 Swing 组件使用包装类,目前是 JPanel
和 JLabel
。面板使用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);
}
有什么建议吗?
I'm currently stuck with the following problem:
I need to dynamically update component positioning at run time. I'm making a form editor for an external application. I use wrapper-classes for standard Swing components, currently JPanel
and JLabel
. Panels are using TableLayout
. I'm storing each component position in a field for each component. When something is changed, I need to recursively update all positions. Here is my method for updating positions:
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();
}
I know, it's rough, but it's not working. All the components are seems to belong to 0,0 grid cell. X's and Y's are correct, as I've seen through debugger. Here is how I add components to my panel:
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);
}
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JComponent.getTopLevelAncestor().验证()
JComponent.getTopLevelAncestor().validate()
我终于用以下代码解决了这个问题:
这意味着,完全重新创建所有布局是有效的。谢谢大家的帮助!
I have finally solved it with the following code:
Which means, fully re-creating all layouts is working. Thanks everyone for help!