创建一种声明性 XML UI 语言:用 Java 语言构建一个 UI 和配套框架
2009-10-19 00:00:00 来源:WEB开发网添加到一个容器组件
另一个值得探讨的部分是容器类型 XUIWindow,它是 XUIComponent 的间接子类型。XUIWindow 实现表示一个 javax.swing.JFrame 组件,因此它必须允许将子元素添加到布局中。清单 6 展示了它的实现。首先必须确保只有某些类型的子元素可以添加到 XUIWindow 中。这样,XUIComponent 的 DOM 节点表示(XUINode)将被检索以便访问该元素的属性。注意,这要求所有 XUIComponent 的构造器初始化这些值。
下面进一步检查以确保以下两点:该组件是一个中级容器(比如 XUIPanel);这个中级容器能够包含在 XUIWindow 的行列网格中。最后,将组件添加到 XUIWindow 要确保以下两点:组件已启用并在布局网格中设置了正确的位置;XUIWindow 的 XUINode(win 变量)获得了一个引用 —— 引用新的子组件的 XUINode,即 addChildNode() 调用。
清单 6. XUIWindow addComponent 方法实现
public void addComponent(XUIComponent component) throws XUITypeFormatException {
if(component instanceof XUIBasicDialog
|| component instanceof XUIOpenFileDialog
|| component instanceof XUICustomDialog
|| component instanceof XUIMenuBar
|| component instanceof XUIPanel
|| component instanceof XUISplitPanel
|| component instanceof XUITabbedPanel
|| component instanceof XUISaveFileDialog) {
// get the node
XUINode node = component.getNodeRepresentation();
if(!(component instanceof XUIMenuBar)) {
int x = Integer.parseInt(node.getAttributeValue("x"));
int y = Integer.parseInt(node.getAttributeValue("y"));
int width = Integer.parseInt(node.getAttributeValue("width"));
int height = Integer.parseInt(node.getAttributeValue("height"));
// can't add dialogs so need to check for type here.
if(component instanceof XUIBasicDialog
|| component instanceof XUIOpenFileDialog
|| component instanceof XUICustomDialog
|| component instanceof XUISaveFileDialog) ; // nothing
else {
// check to make sure it fits within the grid.
Dimension localGrid = this.getGrid();
if(width > localGrid.getWidth() || height >
localGrid.getHeight()) {
throw new XUITypeFormatException(node.getName()
+ " (id: " + node.getAttributeID()
+ ") must be within this window's grid width and"
+ "height (w: " + localGrid.getWidth()
+ " + h: " + localGrid.getHeight() + ")");
}
Rectangle rect = new Rectangle(y, x, width, height);
component.getPeer().setEnabled(true);
frame.getContentPane().add(component.getPeer(), rect);
// for mapping components to the regions they occupy
childComponentMappings.put(component, rect);
}
component.setComponentLocation(x, y);
} else {
// do specifics for a menubar
frame.setJMenuBar((JMenuBar)component.getPeer());
}
frame.invalidate();
frame.validate();
// add the component's node
int level = win.getLevel();
node.setLevel(++level);
if(win.getParent() == null)
win.addChildNode(node);
} else {
StringBuffer sb = new StringBuffer();
sb.append("Type not supported in XUIWindow. ");
sb.appen("The following types are supported:\n");
for(int i = 0; i < supportedComponents.size(); i++) {
String s = (String)supportedComponents.get(i);
sb.append("- " + s + "\n");
}
throw new XUITypeFormatException(sb.toString());
}
}
更多精彩
赞助商链接