JavaFX與SWT彼此之間透過javafx.embed.swt.FXCanvas類別所建立的JavaFX Canvas處理,以便在SWT程式中使用JavaFX類別,FXCanvas類別繼承自SWT的Canvas類別,因此JavaFX Canvas可視為畫布 (Canvas) ,用以配置JavaFX物件。
以下範例示範在以SWT中以FXCanvas類別建立JavaFX Canvas並配置JavaFX物件,其中以Button類別建立圖像按鈕:
// JavaFX API
import
javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Scene;
import
javafx.embed.swt.FXCanvas;
import
javafx.scene.control.Button;
import
javafx.scene.control.ContentDisplay;
import
javafx.scene.image.Image;
import
javafx.scene.image.ImageView;
import
javafx.event.ActionEvent;
import
javafx.event.EventHandler;
import javafx.scene.Group;
// SWT API
import
org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.RowLayout;
/**
*
*
@author Leo Huang
*/
public class SWTDemo {
public static void main(String[] args) {
final org.eclipse.swt.widgets.Display display =
new
org.eclipse.swt.widgets.Display();
final org.eclipse.swt.widgets.Shell shell =
new
org.eclipse.swt.widgets.Shell(display);
final org.eclipse.swt.layout.RowLayout layout =
new
org.eclipse.swt.layout.RowLayout();
shell.setLayout(layout);
//
Create SWT button
final org.eclipse.swt.widgets.Button swtButton =
new
org.eclipse.swt.widgets.Button(shell, SWT.PUSH);
swtButton.setText("SWT Button");
swtButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
swtButton.setText("SWT Event");
shell.layout();
}
});
//
Create FXCanvas
final FXCanvas fxCanvas = new FXCanvas(shell, SWT.NONE) {
public Point computeSize(int wHint, int hHint, boolean changed) {
getScene().getWindow().sizeToScene();
int width = (int) getScene().getWidth();
int height = (int)
getScene().getHeight();
return new Point(width, height);
}
};
//
Create JavaFX button
final Button jfxButton = new Button();
jfxButton.setText("JavaFX Button");
jfxButton.setGraphic(new ImageView(new Image(
SWTDemo.class.getResourceAsStream("images/dukeswing.gif"))));
jfxButton.setContentDisplay(ContentDisplay.TOP);
jfxButton.setPrefWidth(100);
jfxButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
jfxButton.setText("JavaFX Event");
shell.layout();
}
});
Group root = new Group();
root.getChildren().add(jfxButton);
Scene scene = new Scene(root);
fxCanvas.setScene(scene);
shell.pack();
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
|
【執行結果】
【參考資料】
[1] 黃嘉輝,深入研究JavaFX 2。
[2] 黃嘉輝,深入研究Java Swing。
[3] Java Official Web Site:http://www.oracle.com/technetwork/java/index.html
[5] JavaFX 2.2 API Specification.
[6] Java Platform, Standard Edition 7 API Specification.
© Chia-Hui Huang
沒有留言:
張貼留言