JComponent
有没有办法让其后代组件层次结构中的添加/删除变更通知?收听后代组件层次结构变化
例如,在下面的代码中有一个addChild
按钮,它会将新的子项JPanel
添加到根或添加的最后一个面板。我希望根面板获得此通知。有点像HierarchyListener
,但其他方式或ContainerListener
不仅仅是听到直接的孩子。
public class DecendantHierarchyListening extends JFrame {
private final JPanel root = createChildPanel(null);
public JPanel leafComponent = root;
public DecendantHierarchyListening() {
super("title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent buttons = new JPanel();
JPanel panel = new JPanel(new BorderLayout());
panel.add(createAddChildButton(buttons), BorderLayout.NORTH);
panel.add(root, BorderLayout.CENTER);
getContentPane().add(panel);
}
private Button createAddChildButton(JComponent buttons) {
Button button = new Button("AddChild");
buttons.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
leafComponent = (JPanel) leafComponent
.add(createChildPanel(leafComponent));
DecendantHierarchyListening.this.invalidate();
DecendantHierarchyListening.this.validate();
DecendantHierarchyListening.this.repaint();
}
});
return button;
}
public static JPanel createChildPanel(Container parent) {
Color[] colors = new Color[] { Color.RED, Color.BLUE, Color.GREEN };
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 200));
Color color;
if (parent == null) {
color = Color.GREEN;
} else {
int distance = 1;
parent = parent.getParent();
while (parent != null) {
distance++;
parent = parent.getParent();
}
color = colors[distance % colors.length];
}
panel.setBorder(BorderFactory.createLineBorder(color, 2));
return panel;
}
public static void runDemo() {
JFrame f = new DecendantHeirarchyListening();
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
DecendantHierarchyListening.runDemo();
}
}
我想你可以解决这很容易地。为什么你甚至想听一些不影响特定组件的事件?例如,您可以为您想要接收通知的所有容器重新使用一个ContainerListener。在技术上向组件的孩子添加孩子不会影响它(除非您对第一个孩子进行了调整)。这是另一种方法:使用层次结构“中间”的组件通知您的顶级组件。 – J4v4 2014-08-29 15:23:45