简体   繁体   中英

What is the best way to find a composite?

I have SWT Application (Shell), with a few composite : A menu bar is inside a composite, also I have a second composite with various elements.

From the action listener of my menu bar, I would like to access one the element of the second composite.

Currently, I find my composite by doing this. Is there a better/simpler way ?

Control[] appComposites;
appComposites = parent.getChildren();
Composite remoteFile;
for(int i=0; i<appComposites.length;i++){
    if(appComposites[i].toString().compareTo("RemoteFile {}") == 0){
        remoteFile = (Composite) appComposites[i];
    }
}
//Now I must make another loop inside remoteFile to find the element that I need ...

You can use the method Widget#setData(Object) to add identification information to Widget s.

Here is an example:

public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(2, true));

    Listener listener = new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            Widget widget = arg0.widget;

            System.out.println(widget.getData().equals("Button 1");
        }
    };

    for(int i = 0; i < 10; i++)
    {
        Button button = new Button(shell, SWT.PUSH);
        button.setText("Button " + i);
        button.setData("Button " + i);

        button.addListener(SWT.Selection, listener);
    }

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

To find out if the Widget you are looking at is the one you are searching for, you could use:

widget.getData().equals("YOUR IDENTIFIER");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM