Today I wanted to create a simple Java SWT GUI Application using Eclipse, but for better clarity I wanted to have every sub-window in a different class. Since I am very new to Java Programming, is there a way to make a different class do its thing just by calling a method? I looked everywhere on the internet, but couldn't find what I was looking for...
Here's what I have so far
Button foo = new Button(shell, SWT.PUSH);
foo.setText("Edit");
foo.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
// Call the other Class file here
break;
}
}
});
Yes. It is possible. I wouldn't call it "calling a class" though, rather "opening another window" in SWT terms.
You simply wrap a Shell in your other class, then call the open() API from "outside".
If you want to edit something, you could even create wizards.
There are many ways to do what you want to do, I simply chose one of the simple versions. But this is not the only way to do it. Wait for Baz to answer, he'll come along with another cool example. ;)
I would recommend you read the Shell's javadoc, too.
Example:
ShellTest.class (run this as Java Application)
/**
*
* #author ggrec
*
*/
public class ShellTest
{
// ==================== 2. Instance Fields ============================
private AnotherShell anotherShell;
// ==================== 3. Static Methods =============================
public static void main(final String[] args)
{
new ShellTest();
}
// ==================== 4. Constructors ===============================
private ShellTest()
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
anotherShell = new AnotherShell();
createContents(shell);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if ( !display.readAndDispatch() )
display.sleep();
}
display.dispose();
}
// ==================== 5. Creators ===================================
private void createContents(final Composite parent)
{
final Button buttonOpen = new Button(parent, SWT.PUSH);
buttonOpen.setText("Open");
buttonOpen.addSelectionListener(new SelectionAdapter()
{
#Override public void widgetSelected(final SelectionEvent e)
{
anotherShell.open();
}
});
final Button buttonClose = new Button(parent, SWT.PUSH);
buttonClose.setText("Close");
buttonClose.addSelectionListener(new SelectionAdapter()
{
#Override public void widgetSelected(final SelectionEvent e)
{
anotherShell.close();
}
});
}
}
AnotherShell.class (this would be your "other class")
/**
*
* #author ggrec
*
*/
public class AnotherShell
{
// ==================== 2. Instance Fields ============================
private Shell shell;
// ==================== 4. Constructors ===============================
public AnotherShell()
{
shell = new Shell(Display.getCurrent());
}
// ==================== 6. Action Methods =============================
public void open()
{
shell.open();
}
public void close()
{
// Don't call shell.close(), because then
// you'll have to re-create it
shell.setVisible(false);
}
}
Related
I'm using the current version of SWT to build my applications and I want to run it under Mac OS X (Yosemite).
My problem is now that I'm not be able to capture clicks on the "About", "Preferences" and "Quit" menu items which were automatically added to my application.
I already searched a lot and found the following class which seems very helpful to me http://www.transparentech.com/files/CocoaUIEnhancer.java.
And that's my code to initialize it:
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class Test {
private Display display;
private Shell shell;
public Test(Display display) {
this.display = display;
initUI();
}
public void open() {
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
private void initUI() {
shell = new Shell(display);
shell.setSize(808, 599);
shell.setText("Test");
AboutHandler aboutHandler = new AboutHandler();
PreferencesHandler preferencesHandler = new PreferencesHandler();
QuitHandler quitHandler = new QuitHandler();
CocoaUIEnhancer uienhancer = new CocoaUIEnhancer("Test");
uienhancer.hookApplicationMenu(display, quitHandler, aboutHandler, preferencesHandler);
}
private class AboutHandler implements Listener {
public void handleEvent(Event e) {
}
}
private class PreferencesHandler implements Listener {
public void handleEvent(Event e) {
}
}
private class QuitHandler implements Listener {
public void handleEvent(Event e) {
}
}
}
I can compile it without any errors but if I start the program then I will get the following exception:
Exception in thread "main" java.lang.NoSuchMethodError: actionProc
at org.eclipse.swt.internal.Callback.bind(Native Method)
at org.eclipse.swt.internal.Callback.<init>(Unknown Source)
at org.eclipse.swt.internal.Callback.<init>(Unknown Source)
at org.eclipse.swt.internal.Callback.<init>(Unknown Source)
at CocoaUIEnhancer.initialize(CocoaUIEnhancer.java:124)
at CocoaUIEnhancer.hookApplicationMenu(CocoaUIEnhancer.java:92)
at Test.initUI(Test.java:50)
at Test.<init>(Test.java:18)
It's probably an error in the native libraries but I can't figure it out!
I didn't use CocoaUIEnhancer at all, as it was causing issues as well.
So here's what I ended up doing in my applications:
/**
* Convenience method that takes care of special menu items (About, Preferences, Quit)
*
* #param name The name of the menu item
* #param parent The parent {#link Menu}
* #param listener The {#link Listener} to add to the item
* #param id The <code>SWT.ID_*</code> id
*/
private void addMenuItem(String name, Menu parent, Listener listener, int id)
{
if (OSUtils.isMac())
{
Menu systemMenu = Display.getDefault().getSystemMenu();
for (MenuItem systemItem : systemMenu.getItems())
{
if (systemItem.getID() == id)
{
systemItem.addListener(SWT.Selection, listener);
return;
}
}
}
/* We get here if we're not running on a Mac, or if we're running on a Mac, but the menu item with the given id hasn't been found */
MenuItem item = new MenuItem(parent, SWT.NONE);
item.setText(name);
item.addListener(SWT.Selection, listener);
}
Just call it with SWT.ID_PREFERENCES, SWT.ID_ABOUT and SWT.ID_QUIT respectively. Hand in a fallback menu item name, a fallback Menu and the actual Listener you want to add to the menu item.
So for example:
addMenuItem("Quit", myMenu, new Listener()
{
#Override
public void handleEvent(Event event)
{
// Close database connection for example
}
}, SWT.ID_QUIT);
It looks like this the actionProc
int actionProc( int id, int sel, int arg0 )
in CocoaUIEnhancer probably needs to use long rather than int for the arguments to work with 64 bit SWT.
You need to modify CocoaUIEnhancer.java, to make it work with pure SWT application as described in this tutorial:
Modify the getProductName() method to return a String when no product is found (instead of null)
Wrap the code in hookWorkbenchListener() in a try-catch (IllegalStateException e) block
Wrap the code in modifyShells() in a try-catch (IllegalStateException e) block
Add some code to the actionProc(...) method, to bring up an About-Dialog and Preferences-Dialog (since we aren’t using commands):
static long actionProc(long id, long sel, long arg0) throws Exception {
// ...
else if (sel == sel_preferencesMenuItemSelected_) {
showPreferences();
} else if (sel == sel_aboutMenuItemSelected_) {
showAbout();
}
return 0;
}
private static void showAbout() {
MessageDialog.openInformation(null, "About...",
"Replace with a proper about text / dialog");
}
private static void showPreferences() {
System.out.println("Preferences...");
PreferenceManager manager = new PreferenceManager();
PreferenceDialog dialog = new PreferenceDialog(null, manager);
dialog.open();
}
// ...
Finally, we add the following lines to our main() method:
public static final String APP_NAME = "MyApp";
public static void main(String[] args) {
//in your case change the Test constructor
Display.setAppName(APP_NAME);
Display display = Display.getDefault();
//insert in initUI method call the earlysetup
if (SWT.getPlatform().equals("cocoa")) {
new CocoaUIEnhancer().earlyStartup();
}
Shell shell = new Shell(display);
shell.setText(APP_NAME);
...
}
Quoted code.
Baz's solution works great! If you'd rather not import OSUtils just to test if you are on a Mac, use instead:
System.getProperty("os.name").contentEquals("Mac OS X")
I need to know if there is any way to open a shell and not make it active, even if i click a control in it. The best way to explain what i need is to show you this little example. I need to keep the first shell active, even if i click the second one, or any widget that it contains.
public class TestMeOut
{
public static void main(final String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
final Shell shell2 = new Shell(shell);
shell2.setLayout(new GridLayout());
final Button btn = new Button(shell, SWT.PUSH);
final Button btn2 = new Button(shell2, SWT.PUSH);
btn.setText("Test me");
btn2.setText("I steal focus");
btn.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
shell2.setVisible(true);
}
});
btn2.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
shell2.setVisible(false);
}
});
shell.pack();
shell.open();
shell.addShellListener(new ShellListener()
{
public void shellIconified(final ShellEvent e)
{
}
public void shellDeiconified(final ShellEvent e)
{
}
public void shellDeactivated(final ShellEvent e)
{
System.out.println("Deactivated! This isn't supposed to happen.");
}
public void shellClosed(final ShellEvent e)
{
}
public void shellActivated(final ShellEvent e)
{
System.out.println("Activated!");
}
});
shell2.pack();
shell2.open();
shell2.setVisible(false);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Thank you in advance!
You can change the style of your second Shell and use SWT.APPLICATION_MODAL which will make sure that you cannot interact with the parent shell unless you close the child shell:
final Shell shell2 = new Shell(shell, SWT.SHELL_TRIM | SWT.APPLICATION_MODAL);
The modality of an instance may be specified using style bits. The modality style bits are used to determine whether input is blocked for other shells on the display. The PRIMARY_MODAL style allows an instance to block input to its parent. The APPLICATION_MODAL style allows an instance to block input to every other shell in the display. The SYSTEM_MODAL style allows an instance to block input to all shells, including shells belonging to different applications.
Even SWT.PRIMARY_MODAL would suffice in this case.
UPDATE
If on the other hand you don't want the parent to loose focus when the child is clicked, just disable the child:
shell2.setEnabled(false);
So I've stolen this cool PopupComposite, and I am really satisfied with it.
There's just one issue. If it put a org.eclipse.swt.widgets.Text in it, I open the popup, focus the Text, and press ESC, then both the Text and the PopupComposite dispose themselves.
I really can't figure out where the dispose call is coming from. Is it a Shell issue? What Shell should I use with the popup?
SSCCE:
/**
*
* #author ggrec
*
*/
public class PopupCompositeTester
{
public static void main(final String[] args)
{
new PopupCompositeTester();
}
private PopupCompositeTester()
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
createContents(shell);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if ( !display.readAndDispatch() )
display.sleep();
}
display.dispose();
}
private static void createContents(final Composite parent)
{
final Button button = new Button(parent, SWT.PUSH);
button.setText("Poke Me");
final PopupComposite popup = new PopupComposite(parent.getShell());
new Text(popup, SWT.NONE);
popup.pack();
button.addSelectionListener(new SelectionAdapter()
{
#Override public void widgetSelected(final SelectionEvent e)
{
popup.show( Display.getDefault().map(parent, null, button.getLocation()) );
}
});
}
}
The reason for this is because when you focus the text field and press Escape, the field sends a SWT.TRAVERSE_ESCAPE event to its parent shell. The shell (in your case not being a top-level shell) responds by calling Shell.close(). You can work around that by adding a traverse listener to your text field, which would cancel the event (code below).
new Text(popup, SWT.NONE).addTraverseListener(new TraverseListener() {
#Override
public void keyTraversed(TraverseEvent e) {
if(e.detail == SWT.TRAVERSE_ESCAPE) {
e.doit = false;
}
}
});
Keep in mind, this is a rather crude solution to your specific issue. I would not recommend using this for anything other than testing purposes. You can read more about this here -> http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fswt%2Fevents%2FTraverseEvent.html
And here: http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fswt%2Fwidgets%2FShell.html
Because my "bug" is actually a normal behaviour of the SWT platform, I've used the following workaround:
/**
* Lazy initialization of the popup composite
*/
private void createPopup()
{
// popupContainer is now a field
if (popupContainer != null && !popupContainer.isDisposed())
return;
// ... create popup AND its contents ...
}
and in the button listener:
createPopup();
popup.show( Display.getDefault().map(parent, null, button.getLocation()) );
Thank you #blgt
Question:
Can you show any simple example or explanation of SWT display part(which updates the window/shell)? Or can you any sites that you think they are the best for SWT application development?
Background:
I am new to SWT application and currently building an application for running some tests.
It has a main display shell class with text area which keeps getting updated after user clicked on a run button.
The run button starts another thread process which updates public static object such as AtomicCounter in the StartView class.
Current Stage
The program seems running well, however, it does not update the text area in realtime.
Well, I can't say realtime but it shows a little bit delayed information.(I can say it's delayed because I print out on the console as well)
It seems like I don't understand displaying concept of SWT well enough to do whatever I am trying to do with it.
Goal
A. Main Display class which starts and stops C regardless of B running or not
B. Threaded process which updates text area of A class with public static object of A
C. Threaded process which does its job and updating public static object of A
Example Code (Working Code)
public class UnitTest {
public static Display display;
private Shell shell;
public static AtomicInteger counter = new AtomicInteger(0);
public static Text text;
private TestThread test1 = null, test2 = null;
public UnitTest()
{
display = Display.getDefault();
this.shell = new Shell(display, SWT.CLOSE);
this.shell.setSize(226, 120);
text = new Text(shell, SWT.BORDER);
text.setBounds(10, 10, 199, 19);
Button btnStart = new Button(shell, SWT.NONE);
btnStart.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
test1 = new TestThread();
test1.start();
test2 = new TestThread();
test2.start();
}
});
btnStart.setBounds(10, 54, 94, 28);
btnStart.setText("Start");
Button btnStop = new Button(shell, SWT.NONE);
btnStop.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
test1.interrupt();
test2.interrupt();
counter.set(0);
}
});
btnStop.setBounds(115, 54, 94, 28);
btnStop.setText("Stop");
this.shell.open();
this.shell.layout();
this.shell.addListener(SWT.Close, new Listener(){
public void handleEvent(Event event)
{
shell.dispose();
}
});
while(!this.shell.isDisposed())
{
if(!display.readAndDispatch())
{
//text.setText(""+counter.get());
display.sleep();
}
}
}
public static void main(String[] args)
{
new UnitTest();
}
}
class TestThread extends Thread
{
public void run()
{
try
{
int i = 0;
while(i++ < 1000 && !this.isInterrupted() )
{
UnitTest.counter.getAndIncrement();
try {
TestThread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
break;
}
if(UnitTest.display.isDisposed())
return;
UnitTest.display.asyncExec(new Runnable() {
public void run() {
if (UnitTest.text.isDisposed())
return;
UnitTest.text.setText(""+UnitTest.counter.get());
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("Existing thread...");
}
}
}
You should carefully use UI updates from separate threads. Please, read this:
http://goo.gl/At8hC
I am really needing to understand how parent/child dialogs work.
My users use a OTB Application called Teamcenter. I am writing a add on application that is invoked from a menu selection in the Teamcenter Application.
When they click the menu item, that executes a handler class and that creates the base dialog for my application.
public class AplotDialogHandler extends AbstractHandler {
private static AplotBaseDialog dlg = null;
public AplotDialogHandler() {
}// end Constructor
//////////////////////////////////////////////////////////////////////////
// execute() //
//////////////////////////////////////////////////////////////////////////
#Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
if (dlg == null) {
try {
AbstractAIFApplication app = AIFDesktop.getActiveDesktop().getCurrentApplication();
TCSession session = (TCSession) app.getSession();
TCUserService userService = session.getUserService();
AplotVersion.negotiateVersion(userService);
AplotQueryCapabilities.initialize(userService);
dlg = new AplotBaseDialog(null, session);
}
catch (Exception ex) {
MessageBox.post(HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell(), ex, true);
}
}
dlg.create();
dlg.getShell().setSize(700, 400);
dlg.open();
return null;
}// end execute()
}// end EdiDialogHandler()
Question 1. It seems like my application is not tied to the Teamcenter application. Meaning that I can close Teamcenter and my Application stays open.
Question 2. Should I get the workspace shell and pass it in the base dialog?
But even when my application is open, the user still needs to be able to use the Teamcenter application to select data to send to my application
Question 3. When opening dialogs from my base dialog, should I always pass the base dialog shell to those dialogs?
Question 4. Is there a standard way I should close down the dialogs when the user is done?
You need to pass the parent Shell to the dialog so that when you close parent shell, child shells will also be closed.
You should make your dialog MODELESS ( use SWT.MODELSS as style. Note: it is Hint) so that it will not block your parent shell.
Here is sample code:
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
shell.setSize(200, 200);
Button b = new Button(shell, SWT.NONE);
b.setText("Click");
b.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
CDialog dialog = new CDialog(shell);
dialog.open();
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static class CDialog extends Dialog
{
/**
* #param parentShell
*/
protected CDialog(Shell parentShell) {
super(parentShell);
}
/* (non-Javadoc)
* #see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
#Override
protected Control createDialogArea(Composite parent) {
Composite comp = (Composite) super.createDialogArea(parent);
Label lbl = new Label(comp, SWT.NONE);
lbl.setText("Test modeless dialog");
return comp;
}
/* (non-Javadoc)
* #see org.eclipse.jface.window.Window#getShellStyle()
*/
#Override
protected int getShellStyle() {
return SWT.DIALOG_TRIM|SWT.MODELESS;
}
}