更改Container对象中的约束

时间:2017-10-18 15:20:38

标签: layout java-8 containers

在Java 8中, Container 类具有 void add(组件comp,对象约束)方法,该方法为组件添加约束信息。我想构建一个带有三个面板的GUI,按下按钮将导致切换不包含按钮对象的组件的约束信息。如何切换约束信息?

修改 我尝试了以下方法:

    private Map<SpecUITitlePanel, GridBagConstraints> constraints = new Hashtable<SpecUITitlePanel, GridBagConstraints>();
    […]
        switchPanelsButton.setText( "Switch panels");
        switchPanelsButton.addActionListener( new java.awt.event.ActionListener() {
          public void actionPerformed( final java.awt.event.ActionEvent event) {
            switchPanelsActionPerformed( event);
          }
    […]

    private void switchPanelsActionPerformed( final java.awt.event.ActionEvent event) {
      boolean swapped = false;
      final GridBagLayout layout = (GridBagLayout) getLayout();
      final Iterator<SpecUITitlePanel> keysIter = constraints.keySet().iterator();
      // summaryPanel, testPanel

      while (keysIter.hasNext() && layout != null) {
        final SpecUITitlePanel key = keysIter.next();

        final String title = key.getTitle();
        final Iterator<SpecUITitlePanel> keysIter2 = constraints.keySet().iterator();

        while (keysIter2.hasNext()) {
          final SpecUITitlePanel key2 = keysIter2.next();

          final String title2 = key2.getTitle();

          if (!title.equals( title2)) {
            if (!title.contains( BUTTON_PANEL_TITLE) && !title2.contains( BUTTON_PANEL_TITLE)) {
              // swap components
              String message = "component = " + title + ", "
                + constraints.get( key) + "; component2 = " + title2
                + ", " + constraints.get( key2);

              System.out.println( message);
              final GridBagConstraints value = constraints.get( key);
              final GridBagConstraints value2 = constraints.get( key2);

              constraints.put(key, value2);
              layout.setConstraints( key, value2);
              constraints.put(key2, value);
              layout.setConstraints( key2, value);
              swapped = true;
              message = "component = " + title + ", "
                + constraints.get( key) + "; component2 = " + title2
                + ", " + constraints.get( key2);

              System.out.println( message);
          }
        }
      }
    }
    if (swapped) {
      repaint();
    }
  }

输出的相关部分是

component = Test, java.awt.GridBagConstraints@5179288b; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints@f1a7ed2
component = Test, java.awt.GridBagConstraints@f1a7ed2; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints@5179288b

0 个答案:

没有答案