Reputation: 4234
I need to access gui components outside the class that defines them. My gui class contain the following code for placing object on it:
/**
* Create contents of the window.
*/
protected void createContents() {
shlCertificatesmanager = new Shell(Display.getDefault());
shlCertificatesmanager.setSize(450, 300);
shlCertificatesmanager.setText("CertificatesManager");
shlCertificatesmanager.setLayout(new RowLayout(SWT.HORIZONTAL));
MenuItemListener menuListener = new MenuItemListener(shlCertificatesmanager);
Menu menu = new Menu(shlCertificatesmanager, SWT.BAR);
shlCertificatesmanager.setMenuBar(menu);
MenuItem mntmNewSubmenu = new MenuItem(menu, SWT.CASCADE);
mntmNewSubmenu.setText("File");
Menu menu_1 = new Menu(mntmNewSubmenu);
mntmNewSubmenu.setMenu(menu_1);
MenuItem mntmOpenCertificate = new MenuItem(menu_1, SWT.NONE);
mntmOpenCertificate.setText("Open Certificate");
mntmOpenCertificate.addSelectionListener(menuListener);
MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
mntmExit.addSelectionListener(menuListener);
mntmExit.setText("Exit");
MenuItem mntmHelp = new MenuItem(menu, SWT.CASCADE);
mntmHelp.setText("Help");
Menu menu_2 = new Menu(mntmHelp);
mntmHelp.setMenu(menu_2);
MenuItem mntmAbout = new MenuItem(menu_2, SWT.NONE);
mntmAbout.setText("About");
mntmAbout.addSelectionListener(menuListener);
Label lblAliasName = new Label(shlCertificatesmanager, SWT.NONE);
lblAliasName.setText("Alias name: ");
Label label = new Label(shlCertificatesmanager, SWT.NONE);
label.setText("___________");
}
Now my need is to access some of these component from an external class, in that case i need to access the two labels (lblAliasName, label) from MenuItemListener class.
There is a way to access them? (maybe like Android with a findViewById method or similar?)
Or i need for example made them accessible from the other class in some way? (Creating a calss of gui components that will be used by both MenuItemListener class and GuiWindow class)
Upvotes: 3
Views: 383
Reputation: 170735
No, there is no standard way to do this and you need to make them accessible as usual in Java.
Upvotes: 1
Reputation: 36894
Two options come to my mind:
static
fields and hand them over via getter methods.static
) and create getter methods. The other class would of course have to know the instance of your class to access the methods then.Keep in mind:
If you try to change components from a thread that is not the gui-thread, you will get an SWTException
with value ERROR_THREAD_INVALID_ACCESS
.
You can solve this by using:
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// change/modify components here
}
});
Upvotes: 2