2011-04-22 59 views
2

使用此代码,我可以找到选中哪个选项卡,但我需要使用选项卡内的内容来执行操作。我如何使用层次结构?在Java的GUI层次结构中查找组件

EditPane.addChangeListener(new ChangeListener() { 
// This method is called whenever the selected tab changes 
public void stateChanged(ChangeEvent evt) { 
    JTabbedPane pane = (JTabbedPane)evt.getSource(); 

    // Gets current tab 
    int sel = pane.getSelectedIndex(); 
} 
}); 

选项卡内的组件是JScrollPane

回答

4

您不需要窗格的索引,您需要在下面选择的组件。 使用getSelectedComponent() - 例如

JTabbedPane pane = (JTabbedPane)evt.getSource(); 
JComponent myComponent = pane.getSelectedComponent(); 

为了澄清原来的目标,要操纵住在JScrollPane的客户对象。你错过了一些物体。您需要在ScrollPane中调用getViewport()。getViewportView()方法,在您的JScrollPane中使用 。 (来源:http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html

+0

层次没有一个的getChildren()方法?像一个反向的getParent() – Tim 2011-04-22 15:31:13

+1

@Dasdasd如果你正在寻找的是'Container'类,那么有一个方法'Component [] getComponents()'。 – Howard 2011-04-22 15:53:36

+0

我已经检查过它,但它只返回ViewPorts和ScrollBars,而不是ScrollPane – Tim 2011-04-22 16:05:14

1

@ Dasdasd

I already checked it out but it only returns ViewPorts and ScrollBars 

是的,这是正确的,(probalby有你把JPanel中),那么你必须再次重复你的脚步,直到你不会找到JPanelViewPort,这是可能的得到JComponents另一种方式(S),但是这是很好的教训为JComponents

Component[] components = xxx.getComponents(); 
    for (int i = 0, l = components.length; i < l; i++) { 
    if (components[i] instanceof JScrollPane) { 
     JScrollPane scr = (JScrollPane) components[i]; 
      Component[] components1 = scr.getComponents();n