最近我创建了一个每个窗口都能实现的内部窗口模板。我使用GridLayout作为组件,但我不喜欢结果。因此,我决定使用NetBeans生成的代码创建模板(目前为止的模板模式)。一个没有任何内容的普通窗口。
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 517, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 307, Short.MAX_VALUE)
);
}
在详细了解GroupLayout
时,我了解到我无法像使用GridLayout
或FlowLayout
一样轻松添加组件。也许我必须每次更换组件,或更改可见性等...假设我仍然想使用GroupLayout
,这是向该窗口添加组件的最佳模式?我应该从模板模式“迁移”到装饰器吗?如果是这样,我该怎么做呢?你有什么意见?提前谢谢。
public abstract class InternalWindowTemplate{
private int internalWindowCounter = 0;
private final int xOffset = 30;
private final int yOffset = 30;
Container container;
GridLayout gridLayout;
JInternalFrame internalFrame;
GroupLayout internalFrameLayout;
// overriden methods
public InternalWindowTemplate(String title, boolean isResizable, boolean isClosable, boolean isMaximizable, boolean isIconifiable, int width, int height, int gridRows, int gridColumns){
internalFrame = new JInternalFrame(title, isResizable, isClosable, isMaximizable, isIconifiable);
setContainer();
setGridLayout(gridRows, gridColumns);
setInternalWindowSize(width, height);
setInternalWindowLocation(xOffset, yOffset);
}
public void setContainer(){
container = internalFrame.getContentPane();
}
public Container getContainer(){
return container;
}
public void setInternalWindowCloseOperation(){
internalFrame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
}
public JInternalFrame showInternalFrame(){
internalFrame.setVisible(true);
setInternalWindowCloseOperation();
return internalFrame;
}
public void closeInternalFrame(){
internalFrame.dispose();
}
public void addComponentToInternalWindow(Component component){
getContainer().add(component);
pack();
}
public void pack(){
internalFrame.pack();
}
public abstract void addComponentsToInternalWindow();
public void setGridLayout(int rows, int columns){
// I use gridLayout for internal windows
gridLayout = new GridLayout(rows, columns);
getContainer().setLayout(gridLayout);
}
}