我的问题是如何访问Swing GUI元素树(主窗口,JPanels,JFrames,JButtons,JTextFields ect)并创建对该树的引用。我需要将其保存在数据结构(例如哈希映射)中,而不要保存在内存文件中(例如,使用序列化)。我需要使用它,以便以后将这些UI元素映射到代码内的相应对象。

编辑:

   JFrame f = new JFrame("Basic GUI");
   JPanel pnl1 = new JPanel();
   JPanel pnl2 = new JPanel();
   JPanel pnl3 = new JPanel();

   JLabel lblText = new JLabel("Test Label");
   JButton btn1 = new JButton("Button");
   JTextField txtField = new JTextField(20);

   public GUISample(){

   pnl1.add(lblText);
   pnl2.add(btn1);
   pnl3.add(txtField);

   f.getContentPane().setLayout(new BorderLayout());
   f.getContentPane().add(pnl2, BorderLayout.EAST);
   f.getContentPane().add(pnl3, BorderLayout.WEST);
   f.getContentPane().add(pnl1, BorderLayout.NORTH);
   visitComponent(f);

   }

   private Map<String, Component> hashMap = new HashMap<String,Component>();

   public Map<String, Component> getComponentsTree(){
      return hashMap;
   }
   public void visitComponent(Component cmp){
      // Add this component
      if(cmp != null) hashMap.put(cmp.getName(), cmp);
      Container container = (Container) cmp;
      if(container == null ) {
          // Not a container, return
          return;
      }
      // Go visit and add all children
      for(Component subComponent : container.getComponents()){
          visitComponent(subComponent);
      }
     System.out.println(hashMap);

    }

最佳答案

我一直在思考这个问题。这是我的建议:

public class ComponentTreeBuilder{
   private Map<String, Component> hashMap = new HashMap<String,Component>();
   public Map<String, Component> getComponentsTree(){
      return hashMap;
   }
   public void visitComponent(Component cmp){
      // Add this component
      if(cmp != null) hashMap.put(cmp.getName(), cmp);
      Container container = (Container) cmp;
      if(container == null ) {
          // Not a container, return
          return;
      }
      // Go visit and add all children
      for(Component subComponent : container.getComponents()){
          visitComponent(subComponent);
      }
   }
}


像这样使用:

Frame myFrame = new JFrame();
// Make sure you add your elements into the frame's content pane by
myFrame.getContentPane(component);
ComponentTreeBuilder cmpBuilder = new ComponentTreeBuilder();
cmpBuilder.visitComponent(myFrame);
Map<String, Component> components = cmpBuilder.getComponentsTree();
// All components should now be in components hashmap


请注意,ComponentTreeBuilder正在使用递归,如果GUI中的组件过多,则可能会引发堆栈溢出异常。

编辑刚刚在实际示例上测试了此代码,并且....它起作用:)

这是代码:

JFrame frame = new JFrame();
frame.getContentPane().add(new JButton());
frame.getContentPane().add(new JButton());
frame.getContentPane().add(new JButton());
frame.getContentPane().add(new JButton());
visitComponent(frame);


这是输出:

09-26 23:09