mx custom component not working in flex - apache-flex

I want to create flex application by which i can verify user age i have use following code can u tell me why i cant see mx component "dialogtitle","dialogcontent""dialogbutton"
<?xml version="1.0" encoding="UTF-8"?>
<mx:VBox creationComplete="{initComponent();}" height="219" width="560" xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="components.*" xmlns:local="*">
<mx:Script><![CDATA[
import com.people.classes.*;
import com.people.interfaces.*;
import com.people.utils.*;
import flash.events.*;
import flash.utils.*;
import mx.binding.*;
import mx.containers.*;
import mx.controls.*;
import mx.core.*;
import mx.events.*;
import mx.styles.*;
import components.DialogTitle.*;
import components.DialogContent.*;
private var birth_str:String;
private var _controller:IControlManager;
private var testDate:Date;
private var i:int;
private var ageErrorTimer:int = 0;
public function _AgeVerify_Spacer1_c() : Spacer
{
var _loc_1:* = new Spacer();
_loc_1.height = 14;
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_HBox1_c() : HBox
{
var _loc_1:* = new HBox();
_loc_1.percentWidth = 100;
_loc_1.setStyle("horizontalAlign", "center");
if (!_loc_1.document)
{
_loc_1.document = this;
}
_loc_1.addChild(_AgeVerify_VBox2_c());
_loc_1.addChild(_AgeVerify_VBox3_c());
_loc_1.addChild(_AgeVerify_VBox4_c());
return _loc_1;
}// end function
public function _AgeVerify_Label4_c() : Label
{
var _loc_1:* = new Label();
_loc_1.text = "Year";
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_Label6_i() : Label
{
var _loc_1:* = new Label();
ageError = _loc_1;
_loc_1.visible = false;
_loc_1.text = "You have supplied an incorrect date. Please try again.";
_loc_1.setStyle("paddingLeft", 19);
_loc_1.setStyle("fontSize", 12);
_loc_1.setStyle("color", 16711680);
_loc_1.id = "ageError";
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_VBox3_c() : VBox
{
var _loc_1:* = new VBox();
_loc_1.setStyle("horizontalAlign", "center");
_loc_1.setStyle("verticalGap", 1);
if (!_loc_1.document)
{
_loc_1.document = this;
}
_loc_1.addChild(_AgeVerify_Label3_c());
_loc_1.addChild(_AgeVerify_ComboBox2_i());
return _loc_1;
}// end function
public function _AgeVerify_Label2_c() : Label
{
var _loc_1:* = new Label();
_loc_1.text = "Month";
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_ComboBox1_i() : ComboBox
{
var _loc_1:* = new ComboBox();
months = _loc_1;
_loc_1.width = 60;
_loc_1.setStyle("fontSize", 11);
_loc_1.id = "months";
BindingManager.executeBindings(this, "months", months);
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_ComboBox3_i() : ComboBox
{
var _loc_1:* = new ComboBox();
years = _loc_1;
_loc_1.width = 100;
_loc_1.setStyle("fontSize", 11);
_loc_1.id = "years";
BindingManager.executeBindings(this, "years", years);
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_Spacer2_c() : Spacer
{
var _loc_1:* = new Spacer();
_loc_1.height = 13;
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_Label3_c() : Label
{
var _loc_1:* = new Label();
_loc_1.text = "Day";
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function initComponent() : void
{
dialogButtons.addEventListener("onOK", onOK);
var _loc_1:* = new Date();
i = 0;
while (i < 31)
{
days_arr.push((i + 1));
var _loc_3:* = i + 1;
i = _loc_3;
}
i = 0;
while (i < 12)
{
months_arr.push((i + 1));
var _loc_3:* = i + 1;
i = _loc_3;
}
i = _loc_1.getFullYear();
while (i > 1899)
{
years_arr.push(i);
var _loc_3:* = i - 1;
i = _loc_3;
}
days.selectedIndex = 0;
months.selectedIndex = 0;
years.selectedIndex = 0;
return;
}// end function
public function _AgeVerify_Label5_i() : Label
{
var _loc_1:* = new Label();
underAge = _loc_1;
_loc_1.visible = false;
_loc_1.setStyle("paddingLeft", 19);
_loc_1.setStyle("fontSize", 12);
_loc_1.setStyle("color", 16711680);
_loc_1.id = "underAge";
BindingManager.executeBindings(this, "underAge", underAge);
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_Label1_i() : Label
{
var _loc_1:* = new Label();
_AgeVerify_Label1 = _loc_1;
_loc_1.setStyle("fontSize", 13);
_loc_1.setStyle("fontWeight", "bold");
_loc_1.setStyle("color", 7105644);
_loc_1.id = "_AgeVerify_Label1";
BindingManager.executeBindings(this, "_AgeVerify_Label1", _AgeVerify_Label1);
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function _AgeVerify_Canvas1_c() : Canvas
{
var _loc_1:* = new Canvas();
if (!_loc_1.document)
{
_loc_1.document = this;
}
_loc_1.addChild(_AgeVerify_Label5_i());
_loc_1.addChild(_AgeVerify_Label6_i());
return _loc_1;
}// end function
public function _AgeVerify_VBox2_c() : VBox
{
var _loc_1:* = new VBox();
_loc_1.setStyle("horizontalAlign", "center");
_loc_1.setStyle("verticalGap", 1);
if (!_loc_1.document)
{
_loc_1.document = this;
}
_loc_1.addChild(_AgeVerify_Label2_c());
_loc_1.addChild(_AgeVerify_ComboBox1_i());
return _loc_1;
}// end function
public function _AgeVerify_VBox4_c() : VBox
{
var _loc_1:* = new VBox();
_loc_1.setStyle("horizontalAlign", "center");
_loc_1.setStyle("verticalGap", 1);
if (!_loc_1.document)
{
_loc_1.document = this;
}
_loc_1.addChild(_AgeVerify_Label4_c());
_loc_1.addChild(_AgeVerify_ComboBox3_i());
return _loc_1;
}// end function
public function _AgeVerify_ComboBox2_i() : ComboBox
{
var _loc_1:* = new ComboBox();
days = _loc_1;
_loc_1.width = 60;
_loc_1.setStyle("fontSize", 11);
_loc_1.id = "days";
BindingManager.executeBindings(this, "days", days);
if (!_loc_1.document)
{
_loc_1.document = this;
}
return _loc_1;
}// end function
public function onOK(event:Event) : void
{
var event:* = event;
testDate = new Date(years.selectedItem, (parseInt(months.selectedItem.toString()) - 1), days.selectedItem);
if (testDate.getFullYear() == years.selectedItem && testDate.getMonth() == (parseInt(months.selectedItem.toString()) - 1) && testDate.getDate() == days.selectedItem)
{
birth_str = months.selectedItem + "/" + days.selectedItem + "/" + years.selectedItem;
if (Formatters.getYearsOld(birth_str) < 13)
{
ageError.visible = false;
underAge.visible = true;
if (ageErrorTimer > 0)
{
clearTimeout(ageErrorTimer);
}
ageErrorTimer = setTimeout(function () : void
{
ageError.visible = false;
underAge.visible = false;
return;
}// end function
, 6000);
}
else
{
_controller.updateAge(birth_str);
visible = false;
}
}
else
{
underAge.visible = false;
ageError.visible = true;
if (ageErrorTimer > 0)
{
clearTimeout(ageErrorTimer);
}
ageErrorTimer = setTimeout(function () : void
{
ageError.visible = false;
underAge.visible = false;
return;
}// end function
, 6000);
}
return;
}// end function
]]></mx:Script>
<mx:DialogTitle title="Age Verification Needed" width="172" height="45"/>
<mx:DialogContent children="[_AgeVerify_Label1_i(), _AgeVerify_Spacer1_c(), _AgeVerify_HBox1_c(), _AgeVerify_Spacer2_c(), _AgeVerify_Canvas1_c()]"/>
<mx:DialogButtons id="dialogButtons" okCaption="CONTINUE"/>

I think its because of your import statements. You only use .* if your importing a package (a folder), whereas these are classes, so just use the following:
import components.DialogTitle;

Related

How to Autolink the url in Trix Editor

When we paste the content in trix-editor the href not getting paste as simple text. How can we make it as a link.
var TrixAutoLinker,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
addEventListener("trix-initialize", function(event) {
return new TrixAutoLinker(event.target);
});
TrixAutoLinker = (function() {
var INPUT, PATTERN, isValidURL;
function TrixAutoLinker(element) {
this.element = element;
this.autoLink = bind(this.autoLink, this);
this.editor = this.element.editor;
this.element.addEventListener("trix-render", this.autoLink);
this.autoLink();
}
TrixAutoLinker.prototype.autoLink = function() {
var currentRange, i, len, range, ref, ref1, results1, url;
ref = this.getURLsWithRanges();
results1 = [];
for (i = 0, len = ref.length; i < len; i++) {
ref1 = ref[i], url = ref1.url, range = ref1.range;
if (this.getHrefAtRange(range) !== url) {
currentRange = this.editor.getSelectedRange();
this.editor.setSelectedRange(range);
if (this.editor.canActivateAttribute("href")) {
this.editor.activateAttribute("href", url);
}
results1.push(this.editor.setSelectedRange(currentRange));
} else {
results1.push(void 0);
}
}
return results1;
};
TrixAutoLinker.prototype.getDocument = function() {
return this.editor.getDocument();
};
TrixAutoLinker.prototype.getDocumentString = function() {
return this.getDocument().toString();
};
TrixAutoLinker.prototype.getHrefAtRange = function(range) {
return this.getDocument().getCommonAttributesAtRange(range).href;
};
PATTERN = /(https?:\/\/\S+\.\S+)\s/ig;
TrixAutoLinker.prototype.getURLsWithRanges = function() {
var match, position, range, results, string, url;
results = [];
string = this.getDocumentString();
while (match = PATTERN.exec(string)) {
url = match[1];
if (isValidURL(url)) {
position = match.index;
range = [position, position + url.length];
results.push({
url: url,
range: range
});
}
}
return results;
};
INPUT = document.createElement("input");
INPUT.type = "url";
INPUT.required = true;
isValidURL = function(value) {
INPUT.value = value;
return INPUT.checkValidity();
};
return TrixAutoLinker;
})();
// ---
// generated by coffee-script 1.9.2

Start a New Game ( running a program with a New Game Button ) JavaFX

I wrote a Snake Game , when it hit it's tail , it will be Game Over and throw an alert. I set a Button in stage of my alert for new game , and i want to use that to run my cod again at first. is there any method or something...
It's my alert class
class alart {
public static void Game_over_alart(int dom) {
dom = (dom - 9) * 10 ;
Label sdom = new Label(Integer.toString(dom));
Stage window = new Stage();
window.setTitle("Game_Over");
Label gameOver = new Label("Game Over");
Label scor = new Label("SCORE : ");
Label best = new Label("BEST : ");
Text newgame = new Text("NEW GAME");
HBox hbox1 = new HBox(2, scor , sdom );
HBox hbox2 = new HBox(2, best);
VBox vbox = new VBox(2, hbox1, hbox2);
gameOver.setStyle(""
+ "-fx-alignment: top;"
+ "-fx-font-size: 40px;"
+ "-fx-font-style: italic;"
+ "-fx-font-weight: bold;"
+ "-fx-font-family: fantasy;"
+ "-fx-text-fill: lightgrey ;");
// + "-fx-background-color: gray");
DropShadow d = new DropShadow(5, Color.BLACK);
ScaleTransition st=new ScaleTransition(Duration.millis(100),newgame);
st.setToX(1.1);
st.setToY(1.1);
st.setFromX(1);
st.setFromY(1);
//st.setAutoReverse(true);
// st.setCycleCount(Animation.INDEFINITE);
gameOver.setEffect(d);
BorderPane b = new BorderPane();
b.setTop(gameOver);
b.setCenter(vbox);
b.setBottom(newgame);
gameOver.setAlignment(Pos.CENTER);
Scene s = new Scene(b, 400, 200);
window.setScene(s);
window.show();
window.setResizable(false);
newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
}
});
newgame.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event1) {
st.play();
}
});
newgame.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event1) {
st.setFromX(1.1);
st.setFromY(1.1);
st.setToX(1);
st.setToY(1);
}
});
}
}
and it's the whole of my code
/**
* Created by Nadia on 12/31/2015.
*/
import javafx.animation.Animation;
import javafx.animation.AnimationTimer;
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import sun.jvm.hotspot.debugger.cdbg.Sym;
import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;
public class Main_Snake extends Application{
Canvas canvas = new Canvas(399, 599);
Rectangle round = new Rectangle(0 ,0 , 400 , 600 );
B_Part snake = new Snake();
B_Part apple = new Apple();
B_Part mane = new Mane();
#Override
public void start(Stage primaryStage) throws Exception {
round.setStroke(Color.BLACK);
round.setFill(Color.WHITE);
StackPane ss = new StackPane();
ss.getChildren().addAll(round, canvas);
BorderPane b = new BorderPane();
b.setBottom(ss);
Scene scene = new Scene(b, 410, 700);
primaryStage.setScene(scene);
primaryStage.setTitle ( "Snake" );
primaryStage.show();
primaryStage.setResizable(false);
play();
}
public void play() {
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 20_000_000) { // payin avordane sor#
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
try {
for ( int i = 0 ; i < 5 ; i++)
mane.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
}finally {
mane.Drow(canvas);
}
try {
apple.Move(canvas.getScene());
}catch (Exception e) {
}finally {
apple.Drow(canvas);
}
try {
snake.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
stop();
alart.Game_over_alart(snake.X.size());
}finally {
snake.Drow(canvas); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
}
lastUpdate = now; // sor#
}
}
};
timer.start();
}
}
abstract class B_Part {
boolean goNorth = true, goSouth = false, goWest = false, goEast = false; ///////////////////////////////////////////////////////
static int GM = 0 ;
int Mx , My ;
static ArrayList<Integer> Mane_x = new ArrayList<>();
static ArrayList<Integer> Mane_y = new ArrayList<>();
static int x, y ; // marbut be apple
static int j = 0;
// int gm_ov = 0; // vase game over shodan
static ArrayList<Integer> X = new ArrayList<>();
static ArrayList<Integer> Y = new ArrayList<>();
static int Domx1 =400 , Domy1 =390 ;
static int Domx2 =400, Domy2 =400 ;
abstract public void Drow(Canvas canvas);
abstract public void Move(Scene scene)throws Game_Over_Exception;
void Point() {
if (X.get(0) == x && Y.get(0) == y)
j = 0;
}
void Game_Over() {
for (int i = 1 ; i < X.size() ; i ++) { // inke mokhtasate sare mar tu mokhtasate tanesh hast ya na
if (X.get(0).equals(X.get(i)) && Y.get(0).equals(Y.get(i))) {
GM = 1;
}
}
for (int i = 0 ; i < Mane_x.size() ; i ++) { // inke mokhtasate sare mar be mane hast ya na
if (X.get(0).equals(Mane_x.get(i)) && Y.get(0).equals(Mane_y.get(i))) {
GM = 1;
}
}
}
}
class Apple extends B_Part {
#Override
public void Move(Scene scene) {
if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) ( Math.random() * 390 + 1 );
y = (int) ( Math.random() * 590 + 1 );
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*
inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide
*/
j = 1;
}
}
#Override
public void Drow(Canvas canvas) {
DropShadow dd = new DropShadow(20,Color.RED);
GraphicsContext a = canvas.getGraphicsContext2D();
a.setFill(Color.RED);
a.setEffect(dd);
a.fillRect( x , y , 9 ,9);
a.setEffect(null);
}
}
class Snake extends B_Part {
Snake() { //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
X.add(400);
Y.add(350);
X.add(400);
Y.add(360);
X.add(400);
Y.add(370);
X.add(400);
Y.add(380);
}
#Override
public void Drow(Canvas canvas) {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--) {
gc.fillRect(X.get(i), Y.get(i), 9, 9);
gc.setStroke(Color.WHITE);
}
}
#Override
public void Move(Scene scene) throws Game_Over_Exception {
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent small) {
switch (small.getText()) {
case "W":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "S":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "A":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "D":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
/* scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getCode()) {
case UP:
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case DOWN:
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case LEFT:
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case RIGHT:
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
*/
Domx1 = X.get(X.size() - 1);
Domy1 = Y.get(Y.size() - 1);
for (int z = X.size() - 1; z > 0; z--) {
X.remove(z);
X.add(z, X.get(z - 1));
Y.remove(z);
Y.add(z, Y.get(z - 1));
}
if (goNorth) {
Y.add(0, Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0, Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0, X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0, X.get(0) - 10);
X.remove(1);
}
Point(); // emtiaz gerefte
if (j == 0) {
X.add(Domx1);
Y.add(Domy1);
X.add(Domx2);
Y.add(Domy2);
Domx2 = Domx1;
Domy2 = Domy1;
System.out.println();
System.out.println("size : "+Mane_x.size() );
System.out.print(" clear : " );
Mane_x.clear();
Mane_y.clear();
System.out.println("size : "+Mane_x.size() );
}
Game_Over();
if ( GM == 1 ) {
throw new Game_Over_Exception("Game Over");
}
if (X.get(0) > 390) {
X.remove(0);
X.add(0, 0);
}
if (X.get(0) < 0) {
X.remove(0);
X.add(0, 400);
}
if (Y.get(0) > 590) {
Y.remove(0);
Y.add(0, 0);
}
if (Y.get(0) < 0) {
Y.remove(0);
Y.add(0, 600);
}
}
}
class Mane extends B_Part{
#Override
public void Drow(Canvas canvas) {
GraphicsContext gc = canvas.getGraphicsContext2D();
for ( int i = 0 ; i < Mane_x.size() ; i++) {
gc.setFill(Color.GRAY);
gc.fillRect(Mane_x.get(i), Mane_y.get(i), 9, 9);
}
//System.out.println(Mane_x.get(i)+" "+Mane_y.get(i));}
}
#Override
public void Move(Scene scene) {
if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
Mx = (int) (Math.random() * 390 + 1);
My = (int) (Math.random() * 590 + 1);
} while (Mx == x && My == y ||
Mane_x.indexOf(Mx) != -1 && Mane_y.get(Mane_x.indexOf(Mx)) == My ||
X.indexOf(Mx) != -1 && Y.get(X.indexOf(Mx)) == My ||
Mx % 10 != 0 || My % 10 != 0
/* Mx == X.get(0) + 10 && My == Y.get(0) || // yeki joloye saresh nayofte (vaghti rast mire)
Mx == X.get(0) - 10 && My == Y.get(0) || // ( vaghti chap mire)
Mx == X.get(0) && My == Y.get(0) + 10 || // yek ta jolo tar az saresh nayofte vaghtti payi
Mx == X.get(0) && My == Y.get(0) - 10*/); // vaghti bala
//sharte chek kardane in ke har maneye random rooye mar ya maneye ghablia nayofte ( sib hamintor )
Mane_x.add(Mx);
Mane_y.add(My);
}
}
}
class Game_Over_Exception extends Exception{
public Game_Over_Exception (String s){
super(s);
}
}
Hand over a restart method to the alert handler. You can do that directly or via interface, e. g.:
public interface GameManager {
public void restart();
}
Your main class must implement that interface:
public class Main_Snake extends Application implements GameManager {
public void restart() {
// TODO: reset playfield & restart game
}
public void play() {
...
try {
snake.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
stop();
alart.Game_over_alart(snake.X.size(), Main_Snake.this);
}
...
}
}
And in your alart class you invoke that method:
class alart {
public static void Game_over_alart(int dom, GameManager gameManager) {
...
newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// TODO: close dialog
// restart game
gameManager.restart();
}
});
...
}
}

Editing PresentationML using openxml

Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.

change color by calling name

Update: Not sure if this code would work, but couldn't get the name of the sprite where c.getChildByName(spName) is null, spName is the string name of the sprite.
private var s:Sprite;
private var s2:Sprite;
private var c:UIComponent;
private var c2:UIComponent;
private function drawQuarterNotes(xx:int,ty:String):void {
if(ty=="up") {
s = new Sprite();
s2 = new Sprite();
c = new UIComponent();
c2 = new UIComponent();
s2.graphics.lineStyle(3,0x333333);
s2.graphics.moveTo(20,0);
s2.graphics.lineTo(20,50);
c2.addChild(s2);
c2.x = xx+16;
c2.y = xx-18;
s.graphics.beginFill(0x333333);
s.graphics.drawEllipse(7,35,18,12);
s.graphics.endFill();
s.name = "asd2";
s.addEventListener(MouseEvent.MOUSE_DOWN,chgColor);
s.addEventListener(MouseEvent.MOUSE_UP,chgColorReset);
c.addChild(s);
c.rotation = -20;
c.x = xx;
c.y = xx;
}
if(ty=="down") {
s2.graphics.lineStyle(3,0x333333);
s2.graphics.moveTo(20,0);
s2.graphics.lineTo(20,50);
c2.addChild(s2);
c2.x = xx+1;
c2.y = xx+35;
s.graphics.beginFill(0x333333);
s.graphics.drawEllipse(7,35,18,12);
s.graphics.endFill();
c.addChild(s);
c.rotation = -20;
c.x = xx;
c.y = xx;
}
addElement(c);
addElement(c2);
}
private function drawQuarterNotes2(xx:int,ty:String):void {
if(ty=="up") {
s = new Sprite();
s2 = new Sprite();
c = new UIComponent();
c2 = new UIComponent();
s2.graphics.lineStyle(3,0x333333);
s2.graphics.moveTo(20,0);
s2.graphics.lineTo(20,50);
c2.addChild(s2);
c2.x = xx+16;
c2.y = xx-18;
s.graphics.beginFill(0x333333);
s.graphics.drawEllipse(7,35,18,12);
s.graphics.endFill();
s.name = "asd1";
s.addEventListener(MouseEvent.MOUSE_DOWN,chgColor);
s.addEventListener(MouseEvent.MOUSE_UP,chgColorReset);
c.addChild(s);
c.rotation = -20;
c.x = xx;
c.y = xx;
}
if(ty=="down") {
s2.graphics.lineStyle(3,0x333333);
s2.graphics.moveTo(20,0);
s2.graphics.lineTo(20,50);
c2.addChild(s2);
c2.x = xx+1;
c2.y = xx+35;
s.graphics.beginFill(0x333333);
s.graphics.drawEllipse(7,35,18,12);
s.graphics.endFill();
c.addChild(s);
c.rotation = -20;
c.x = xx;
c.y = xx;
}
addElement(c);
addElement(c2);
}
private var c:UIComponent = new UIComponent();
private var s1:Sprite = new Sprite();
private var s2:Sprite = new Sprite();
private function init():void
{
s1.name = "shape1";
s2.name = "shape2";
//make sure s2 doesn't appear on top of s1
s2.x = 100;
s1.addEventListener(MouseEvent.MOUSE_DOWN, chgColorBlue);
s1.addEventListener(MouseEvent.MOUSE_UP, chgColorReset);
c.addChild(s1);
c.addChild(s2);
addElement(c);
//change shape1 to red
changeSpriteColor( 'shape1' , 0x990000 );
//change shape2 to grey
changeSpriteColor( 'shape2' , 0x777777 );
}
//change a sprite color by calling its name
private function changeSpriteColor( spName:String , color:uint ):void
{
var child:Sprite = c.getChildByName(spName ) as Sprite;
//make sure the child has been added to the container
if( child != null )
shapeGraphics( child , color );
}
//change a sprite color
private function shapeGraphics( sp:Sprite , color:uint ):void
{
//make sure to clear the graphics , before changing the color
//there are other ways to change the color
//but i'm following your code!
sp.graphics.clear();
sp.graphics.beginFill(0x333333);
sp.graphics.drawEllipse(7,35,18,12);
sp.graphics.endFill();
}
private function chgColorBlue(e:MouseEvent):void
{
shapeGraphics( e.currentTarget , 0x000099 );
}
private function chgColorReset(e:MouseEvent):void
{
shapeGraphics( e.currentTarget , 0x333333 );
}
I assume you're writing this function in the actions of the flash file, and not in a separate .as file. This function will rely on the stage object being set (if you were to port this to a class, you may or may not have to wait for the ADDED_TO_STAGE event.)
function chgColorBlue():void
{
var element = stage.getChildByName('shape1');
element.graphics.beginFill(0x000099);
element.graphics.drawEllipse(7,35,18,12);
element.graphics.endFill();
}
Edit to show example:
You can call this function after creating the object. It defeats the purpose of trying to access the element by the name attribute.
function chgColorBlue(element:Sprite):void
{
element.graphics.beginFill(0x000099);
element.graphics.drawEllipse(7,35,18,12);
element.graphics.endFill();
}

Plugin to add pagination in a Flex Datagrid?

Is there a library or plugin that could be added to a Flex project to add pagination to a Flex Datagrid?
The source code for this paginated datagrid can be found here.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="InitApp()" xmlns:MyComp="*">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.ItemClickEvent;
import mx.controls.Button;
import mx.controls.Alert;
[Bindable]
public var myData:ArrayCollection = new ArrayCollection();
public var orgData:ArrayCollection = new ArrayCollection();
[Bindable]
public var nav:ArrayCollection = new ArrayCollection();
public var pageSize:uint = 10;
public var navSize:uint = 10;
private var index:uint = 0;
private var navPage:uint = 1;
private function InitApp():void
{
for( var x:uint = 1; x <= 500; x++ )
{
var obj:Object = new Object();
obj.Id = x.toString();
obj.Name = "Column " + x.toString();
obj.Street = "5555 Street";
obj.Title = "CEO";
obj.City = "El Paso";
orgData.addItem(obj);
}
refreshDataProvider(index);
createNavBar(Math.ceil(orgData.length/pageSize));
}
private function createNavBar(pages:uint = 1,set:uint = 0):void
{
nav.removeAll();
if( pages > 1 )
{
if( set != 0 )
{
nav.addItem({label:"<<",data:0});
if( (set - navSize ) >= 0 )
{
nav.addItem({label:"<",data:set - navSize});
}
else
{
nav.addItem({label:"<",data:0});
}
}
for( var x:uint = 0; x < navSize; x++)
{
var pg:uint = x + set;
nav.addItem({label: pg + 1,data: pg});
}
if( pg < pages - 1 )
{
nav.addItem({label:">",data:pg + 1});
nav.addItem({label:">>",data:pages - pageSize});
}
}
}
private function navigatePage(event:ItemClickEvent):void
{
refreshDataProvider(event.item.data);
var lb:String = event.item.label.toString();
if( lb.indexOf("<") > -1 || lb.indexOf(">") > -1 )
{
createNavBar(Math.ceil(orgData.length/pageSize),event.item.data);
if( event.item.data == 0 )
{
pageNav.selectedIndex = 0;
}
else
{
pageNav.selectedIndex = 2;
}
}
}
private function refreshDataProvider(start:uint):void
{
myData = new ArrayCollection( orgData.source.slice((start * pageSize),(start * pageSize) + pageSize) );
}
]]>
</mx:Script>
<mx:VBox verticalGap="0">
<mx:DataGrid id="dg" dataProvider="{myData}"></mx:DataGrid>
<mx:ToggleButtonBar id="pageNav" itemClick="navigatePage(event)" dataProvider="{nav}" width="{dg.width}"></mx:ToggleButtonBar>
</mx:VBox>
</mx:Application>

Resources