Maybe a simple question but I'm having alot of trouble making a button change the view of a Flex blackberry playbook app. I am coding it entirely in actionscript, no MXML.
myButton.addEventListener(MouseEvent.CLICK, doSomethingOnClick);
private function doSomethingOnClick(e:MouseEvent):void {
navigator.pushView(view.Login, "testdata");
}
When I try this I get:
1120: Access of undefined property navigator.
Which is weird as it works in a MXML file. How do I change views in actionscript?
Thanks
Phil
EDIT:
Cheer J_A_X, but now i have:
navigator = new ViewNavigator();
navigator.pushView(net.airpoint.assessments.view.Login, " ");
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Apologies, as I realise this is really simple stuff but it just isnt clicking!
Update 2
*Assessments.as*
package
{
import flash.display.Sprite;
import flash.events.Event;
import net.airpoint.assessments.view.*;
import qnx.ui.core.Container;
import qnx.ui.core.ContainerAlign;
import qnx.ui.core.ContainerFlow;
import qnx.ui.core.Containment;
import qnx.ui.text.Label;
import spark.components.ViewNavigator;
[SWF(height="600", width="1024", frameRate="30", backgroundColor="#FFFFFF")]
/* Main Layout */
public class Assessments extends Sprite
{
//containers
private var main:Container;
private var menu:Container
private var firstLabel:Label;
private var navigator:ViewNavigator;
public function Assessments()
{
initializeUI();
}
private function initializeUI():void
{
main = new Container();
main.padding = Vector.<Number>([20,20,20,20]);
main.flow = ContainerFlow.HORIZONTAL;
main.debugColor = 0xFFCC00;
firstLabel = new Label();
firstLabel.text = "First label";
firstLabel.size=35;
main.addChild(firstLabel);
addChild(main);
navigator = new ViewNavigator();
navigator.pushView(Login, " ");
}
}
}
Login.as
package net.airpoint.assessments.view
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import qnx.ui.buttons.Button;
import qnx.ui.core.Container;
import qnx.ui.text.Label;
import qnx.ui.text.TextInput;
import spark.components.View;
public class Login extends View
{
private var usernameLabel:Label;
public function Login()
{
initializeUI();
}
public function initializeUI():void
{
usernameLabel.text = "test";
this.addChild(usernameLabel);
}
}
}
Something isn't right. If it's a Flex Mobile Project, you need an Application at the top level (you know, like how Flash Builder created the project with an mxml file). Either you create an actionscript file that extends Application as mentioned here or you just use an mxml file for the root component.
However, your argument to 'not use mxml' is redundant if you're using Flex components. If you're using Flex components, you're using mxml no matter what, so there's no performance increase. If anything, RIM is recommending to use AS only because their SDK is AS only (which is idiotic anyways). You could always add their UI component through AS in mxml files.
So really, the point is moot and you should just use mxml anyways since it's better than straight AS for UI layout and skinning. Either that or go Pure AS with no Flex components.
I think using Sprite is ok in an ActionScript project.
But if you're using ActionScript instead of Flex just because of the QNX components, then you could switch your project to Flex and follow these instructions to use the QNX components there: Using qnx.ui.picker.Picker in mobile Flex Hero project for Blackberry Playbook
Related
Firstly, I am quite a new guy in coding. I need to embed a font in my java FXML-based app and don't know how to do it. I have pasted the font, fontName.ttf in a "resources" folder in the root of the sources of my project, ie App/src/app/resources. I have set the CSS for the component (text) as
#text {
-fx-font-family: url(resources/fontName.ttf);
}
I have also tried adding inverted commas in the url, ie url("resources/fontName.ttf");, but it doesn't work. I have also set the CSS id for the component, so that can't be the problem. Is there any other working way to do so? I have seen http://fxexperience.com/2010/05/how-to-embed-fonts/, but it doesn't work since I have JDK 1.7 u21. Any ideas for a correct way to embed fonts?
Solution Approach
I updated the sample from Javafx How to display custom font in webview? to demonstrate using a custom true-type font in JavaFX controls styled using CSS.
Key points are:
Place the font in the same location as your application class and ensure your build system places it in your binary build package (e.g. application jar file).
Load the code font in your JavaFX code before you apply a style which uses it.
Font.loadFont(CustomFontApp.class.getResource("TRON.TTF").toExternalForm(), 10);
To use the custom font in a style class use the -fx-font-family css attribute and just reference the name of the font (e.g. in this case "TRON").
Create and load a stylesheet which defines the style classes.
Apply style classes to your controls.
Additional Information
If you are using Java 8, you may be interested in Use web(Google) fonts in JavaFX.
Font Collections
If your font file is in .ttc format, containing multiple fonts in a single file, then use the Font.loadFonts API (instead of Font.loadFont). Note that Font.loadFonts is only available since JDK 9 and is not available in earlier releases.
Sample Output Using a Custom Font
Sample Code
The example relies on a TRON.TTF font which you can download from dafont.
CustomFontApp.java
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.*;
import javafx.stage.Stage;
// demonstrates the use of a custom font.
public class CustomFontApp extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
stage.setTitle("TRON Synopsis");
// load the tron font.
Font.loadFont(
CustomFontApp.class.getResource("TRON.TTF").toExternalForm(),
10
);
Label title = new Label("TRON");
title.getStyleClass().add("title");
Label caption = new Label("A sci-fi flick set in an alternate reality.");
caption.getStyleClass().add("caption");
caption.setMaxWidth(220);
caption.setWrapText(true);
caption.setTextAlignment(TextAlignment.CENTER);
VBox layout = new VBox(10);
layout.setStyle("-fx-padding: 20px; -fx-background-color: silver");
layout.setAlignment(Pos.CENTER);
layout.getChildren().setAll(
title,
new ImageView(
new Image(
"http://ia.media-imdb.com/images/M/MV5BMTY5NjM2MjAwOV5BMl5BanBnXkFtZTYwMTgyMzA5.V1.SY317.jpg"
)
),
caption
);
// layout the scene.
final Scene scene = new Scene(layout);
scene.getStylesheets().add(getClass().getResource("custom-font-styles.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
}
custom-font-styles.css
/** file: custom-font-styles.css
* Place in same directory as CustomFontApp.java
*/
.title {
-fx-font-family: "TRON";
-fx-font-size: 20;
}
.caption {
-fx-font-family: "TRON";
-fx-font-size: 10;
}
On FXML Usage
Font.loadFont(url, size) is a static method taking two parameters. I don't think you can invoke font.loadFont from FXML and wouldn't advise it if you could. Instead, load the font in Java code (as I have done in my answer) before you load your FXML or style sheet which requires the font.
I know you didn't ask for a pure programmatic way to use a custom TTF font in a java fx application but i thought maybe it helps someone to see a programmatic version:
public class Test2 extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(final Stage primaryStage) {
Group rootGroup = new Group();
// create a label to show some text
Label label = new Label("Demo Text");
try {
// load a custom font from a specific location (change path!)
// 12 is the size to use
final Font f = Font.loadFont(new FileInputStream(new File("./myFonts/TRON.TTF")), 12);
label.setFont(f); // use this font with our label
} catch (FileNotFoundException e) {
e.printStackTrace();
}
rootGroup.getChildren().add(label);
// create scene, add root group and show stage
Scene scene = new Scene(rootGroup, 640, 480, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
}
That did the job for me. You can place the font wherever you want just make sure you adapt the path.
You can find a lot more about using fonts inside java fx apps here.
HTH
I mean like in file managers, when you would click, drag the mouse, creating a rectangle selection and after the mouse released selection is created?
I could do that like this (pseude-code like):
onMousePressed:
setGestureStarted(true)
onMouseMoved:
if isGestureStarted:
changeRectangle(event.getX, event.getY)
onMouseReleased:
select(getSelectionRectange())
But I thought that it's pretty common behavior and maybe it's already in framework.
EDIT1:
I was trying to do zoomable linechart. And I actually came across library to do that.
It's pretty good, but could be better though.
Right now I'm considering the actual worth of javaFX in our web project, because I don't like how such thing as zoomable chart is not in the library. Probably would be better with javascript (except I should learn it first, but It shouldn't be that hard).
You would probably need to make your own implementation for this. I found your pseudo code is quiet good. If you like to select for any component then you need to first create a simple rectangular boundary which is easily possible by your pseudo code.
Now for finding out either your node is inside that boundary then you need to do iteration of all the nodes/children of certain Parent Object by using this function: Node Intersect check
I would suggest to use that function after the onMouseReleased or if you like to see things in realtime then it is preferable in onMouseMoved
Your question asks "Is there any implementation of rectangle selection in JavaFX?"
The answer is "yes".
SceneBuilder implements drag-select functionality.
SceneBuilder is open source, so take a look through the source if you are interested on how this behaviour is achieved in JavaFX by SceneBuilder.
SceneBuilderKit is the framework from which SceneBuilder is derived, its source is at the link I provided.
From the SceneBuilder release notes:
JavaFX Scene Builder Kit is an API that allows the integration of Scene Builder panels and functionalities directly into the GUI of a larger application, or a Java IDE, such as NetBeans, IntelliJ, and Eclipse.
where is documentation?
From the release notes:
The javafx_scenebuilder_kit_javadoc-2_0-ea--.zip file, which contains an API javadoc for the JavaFX Scene Builder Kit. You can download the zip file from http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html.
The javafx_scenebuilder_kit_samples-2_0-ea--.zip file, which contains the SceneBuilderHello sample application that shows a minimal Java source code example of how the Scene Builder Kit API can be used. This sample is delivered as a NetBeans project. It can be downloaded from http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html.
Perhaps after you investigate, SceneBuilder and SceneBuilderKit might not be what you are looking for. In which case, edit your question to make it more explicit and perhaps include source for your rectangle selection implementation attempt and more detail on your requirements (what you intending to select, an image showing how the feature works, etc).
yes, in jfxtras-labs project via:
MouseControlUtil.addSelectionRectangleGesture(Parent root, Rectangle rect)
or
MouseControlUtil.addSelectionRectangleGesture(Parent root, Rectangle rect, EventHandler<MouseEvent> dragHandler, EventHandler<MouseEvent> pressHandler, EventHandler<MouseEvent> releaseHandler)
more info: http://jfxtras.org/doc/8.0labs/jfxtras/labs/util/event/MouseControlUtil.html
Note that selection behavior is extremely application specific and the class above is just a helper class to help you with selection gesture implementations. In the end you have to implement selection behavior yourself.
For a more detailed and matured example of node selection in JavaFx see my other answer here.
Edit: Basic Demo
This is the basic usage. Note that it's just a demo and should NOT be considered final or production ready! For more complex implementation of selection behavior you should tailor it (mostly mouse handlers) on your own based on your application's specific requirements.
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import jfxtras.labs.util.event.MouseControlUtil;
public class ShapeSelectionExample extends Application {
private List<Shape> selected = new ArrayList<>();
#Override
public void start(Stage primaryStage) {
final Group shapesGroup = new Group();
final AnchorPane root = new AnchorPane(shapesGroup);
// Add whatever shapes you like...
Rectangle shape1 = new Rectangle(200, 20, 50, 50);
Rectangle shape2 = new Rectangle(300, 60, 50, 50);
Circle shape3 = new Circle(100, 100, 30);
shapesGroup.getChildren().addAll(shape1, shape2, shape3);
final Rectangle selectionRect = new Rectangle(10, 10, Color.TRANSPARENT);
selectionRect.setStroke(Color.BLACK);
EventHandler<MouseEvent> mouseDragHanlder = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
for (Node shape : shapesGroup.getChildren()) {
handleSelection(selectionRect, (Shape) shape);
}
}
};
// Add selection gesture
MouseControlUtil.addSelectionRectangleGesture(root, selectionRect, mouseDragHanlder, null, null);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
}
private void handleSelection(Rectangle selectionRect, Shape shape) {
if(selectionRect.getBoundsInParent().intersects(shape.getBoundsInParent())) {
shape.setFill(Color.RED);
if(!this.selected.contains(shape))
this.selected.add(shape);
} else {
shape.setFill(Color.BLACK);
this.selected.remove(shape);
}
System.out.println("number of selected items:" + this.selected.size());
}
public static void main(String[] args) {
launch(args);
}
}
This is how the result would look like:
You could also write mouse press and release handlers (currently null in this code) to handle selection behavior while mouse button is pressed or released (which is different to mouse drag).
I am trying to learn Flex and Actionscript. I found the Moock quiz example in Flash and want to turn it into a Flex application. I am trying to understand the relationship between the actionscript and the mxml. How do I take the class QuizApp and place its contents in a container in the mxml file?
MXML
<fx:Script>
<![CDATA[
import QuizApp;
var ms:QuizApp = new QuizApp;
protected function init():void
{
msc.addChild(ms);
}
]]>
</fx:Script>
<mx:VBox id="msc" />
Class
package {
import flash.display.Sprite;
import mx.controls.Button;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class QuizApp extends Sprite {
//for managing questions:
private var quizQuestions:Array;
private var currentQuestion:QuizQuestion;
private var currentIndex:int = 0;
public function QuizApp() {
quizQuestions = new Array();
createQuestions();
createButtons();
createStatusBox();
addAllQuestions();
hideAllQuestions();
firstQuestion();
}
... etc
}
}
I am trying to understand the relationship between the actionscript
and the mxml.
MXML is an ActionScript code generation language. When you write MXML, the Flex compiler does some "magic" to turn your MXML file into an ActionScript class. You can save this generated code by specifying the 'keep-generated-actionscript' argument to the Flex Compiler. I'll often shorten it to'-keep' and it works fine.
MXML masks a lot of the complexity that is going on under the scenes.
I hope that helps set your frame of expectations.
To use your "Flex agnostic" ActionScript Sprite Class inside of a MX Flex Container, you should be able to use it just like any other class you create. First, import the namespace at your top level tag of your component:
myNamespace:xmlns="*"
Then you should be able to use it, like this:
<myNamespace:QuizApp id="quizAppInstance" />
If you're using a Flex 4 Spark Container, you need something that implements IVisualElement; which a Sprite does not. However, you can wrap your own class inside of a SpriteVisualElement class without too much effort.
How can I use TweenLite to implement effect of Flex's PopUpManager?
I am using greensock tweenlite for sample
here a code for creating simple tweenlite effect on popup using PopUpManager
import com.greensock.TweenLite;
import mx.managers.PopUpManager;
import mx.containers.TitleWindow;
[Bindable]
private var titleWindow:TitleWindow;
private function createTweenlitePopup():void{
titleWindow=TitleWindow(PopUpManager.createPopUp(this,TitleWindow,true));
titleWindow.title = "This is my title window";
TweenLite.to(titleWindow, 1.5, {x:100});
}
and button calling createTweenlitePopup() to create popup is
<mx:Button click="{createPopup()}"/>
Hopes that helps
I have problem with using next two properties together in one Air application, I need some functionality for show my application in full screen and scale for different displays. I mean , if user has 17" and other has 24" display my app should save proportionals. So, I've start to use these two properties StageScaleMode.SHOW_ALL StageDisplayState.FULL_SCREEN and see that internal canvas (buffer) is bigger than external, please see on the pictures the firs just StageDisplayState.FULL_SCREEN and the second StageDisplayState.FULL_SCREEN and StageScaleMode.SHOW_ALL.
Could you help me and say How to fix this problem?
Thanks.
StageScaleMode.SHOW_ALL ensures the entire content of your Flash Movie is always displayed. Depending on how large your content is, and where you place your images, this might well exceed the actual display width of your screen.
If you want your movie to always center on screen, but not scale its content, do it like this (fullscreen on click):
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
public class Test extends MovieClip
{
private var content : Sprite;
public function Test ()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
content = new Sprite( );
content.graphics.beginFill( 0, 1 );
content.graphics.drawRect( 0, 0, 200, 100 );
content.graphics.endFill( );
addChild( content );
stage.addEventListener( Event.RESIZE, onResize );
content.addEventListener( MouseEvent.CLICK, onMouseClick );
}
public function onMouseClick (ev : Event) : void
{
stage.displayState = StageDisplayState.FULL_SCREEN;
}
public function onResize ( ev : Event ) : void
{
content.x = (stage.stageWidth - content.width) * .5;
content.y = (stage.stageHeight - content.height) * .5;
}
}
}
Then attach all your elements to the content Sprite instead of the stage.
I have developed my own approach for re-sizing without using SHOW_ALL property, but currently it correctly works only on the Windows systems.
The real issue here is that anything except stage.scaleMode = StageScaleMode.NO_SCALE; will not report the actual stage.stageWidth and stage.stageHeight, but will instead return the width and height of the authored dimensions.