简体   繁体   English

获取Java Swing中组件的布局约束

[英]Get layout constraints for a component in Java Swing

Below is a mock up of code that I've been working on. 下面是我一直在研究的代码模拟。



public class Pane {

    private final JPanel pane;
    private JPanel namePanel;
    private final JTextField panIdField;

    public Pane() {
        pane = new JPanel();
        pane.setLayout(new MigLayout("", "[][grow]", "[][][][][]"));

        namePanel = new JPanel();
        pane.add(namePanel, "cell 1 1,growx");

        panIdField = new JTextField();
        pane.add(panIdField, "cell 1 2,growx");
        panIdField.setColumns(10);

    }

    public void replaceNameField(JPanel newNamePanel) {
        this.namePanel = newNamePanel;
        // Object constraintsForNamePanel = 
        pane.remove(namePanel);
        pane.add(newNamePanel, constraintsForNamePanel);
    }

}

In Container there's method 在容器中有方法

public void add(Component comp, Object constraints)

Is there any way that we can programatically get the constraints that we set, like getConstraints(...) so that we can use it for later use? 有没有什么方法可以编程地获取我们设置的constraints ,比如getConstraints(...)以便我们可以将它用于以后使用?

In my code, I want to use it to replace a old component with a new one at the same place. 在我的代码中,我想使用它在同一个地方用新的组件替换旧组件。

What do I have to do after 我该怎么办?

 Object constraintsForNamePanel = 

to get the constraints for namePanel . 获取namePanel的约束。

Currently, I'm using 目前,我正在使用

pane.add(newNamePanel, "cell 1 1,growx");

It is working but the problem is I'm using WindowsBuilder for UI and my UI is like to change when I add new components to the pane and I don't want to copy and paste the constraints. 它正在工作,但问题是我正在使用WindowsBuilder for UI,我的UI就像在我向pane添加新组件时更改,我不想复制和粘贴约束。

Got the solution, I had to do following. 得到了解决方案,我必须做到以下。


public void replaceNameField(JPanel newNamePanel) {
     MigLayout layout = (MigLayout) pane.getLayout();
     Object constraintsForNamePanel = layout.getComponentConstraints(this.namePanel);
     pane.remove(this.namePanel);

      this.namePanel = newNamePanel;
      pane.add(newNamePanel, constraintsForNamePanel);
    }

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

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