今天我想用Eclipse创建一个简单的Java SWT GUI应用程序,但为了更清晰,我想让每个子窗口都在不同的类中。由于我是Java编程的新手,有没有办法让一个不同的类只通过调用一个方法来做它的事情?我在互联网上到处寻找,但找不到我想要的东西......
这是我到目前为止所拥有的
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;
}
}
});
答案 0 :(得分:7)
是。有可能的。我不会称之为“叫一个班级”,而是用SWT术语“打开另一个窗口”。
您只需将Shell
打包到其他课程中,然后从“外部”调用open()
API。
如果你想编辑某事,你甚至可以create wizards。
有很多方法可以做你想做的事情,我只选择了一个简单的版本。但这是不唯一的方法。等待Baz回答,他会再来一个很酷的例子。 ;)
我建议你也阅读Shell
的javadoc。
实施例
ShellTest.class (将其作为Java应用程序运行)
/**
*
* @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 (这将是你的“其他类”)
/**
*
* @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);
}
}