Do you speak Java?

poniedziałek, 28 grudnia 2009

Netbeans 6.8 : JavaFX editor

As we almost all* know modern progaming language is not only semantic, keywords, compiler, additional open source and commercial libraries but also a good editor that simplifys and speedups every day development.

I really like JavaFX but  lets be honest here - JavaFX Script is still missing SOME (I don't want to be too cruel here ;) ) of those features so I am very pleased to see enhanced JavaFX editor in latests  NetBeans IDE 6.8 release.
So what new features  do we get  ?
  • Code formating (FINALLY) - yes yes! it is not a joke! prior to NetBeans 6.8 release there was no code formating for JavaFX Script. But lets forget about this, we have it now and it works pretty well(standard shortcut: alt+shift+F).  I hope that from now on  we will never again see so absurd posts like this one 
  •  finding usage - you can search for usage of methods and variables in JavaFX files. But we can not search for Java members usage in JavaFX files :(
  •  rename refactoring - but again just like in "find usage", changing name of java member wont refactor usage of those memebers in javaFX files. But still it is better to have renaming then not having it ;)
  •  moving classes to an other package

As we can see those enhancements are not so big and still lots of refactoring  and cross Java/JavaFX functionalities are missing, but hey! half a loaf is better than none ;)


[*] cheers for all VIMronosauruses - my favorite type of dinosaur :)

piątek, 4 grudnia 2009

JavaFX static members

Some time ago I have read post about 10 interesting things in JavaFX Script. This post was really nice and I have learned that there is build in support to format Dates  But one point  interested me at most,

No support for static functions, variables and constants

I have already made a comment under post on this point but I would like to make it crystal clear.
There IS support for static members in JavaFX Script. Thats true - there is no "static" key word build in the language, but still you can make function or field static. We just have to put it inside class file but outside class declaration.
I.E.
public class MyClass{
  public function memberFunction(){
  }
}

public function staticFunction(){
}

var staticVar;

def STATIC_CONST; 

and thats it. You can call/access them with:
MyClass.staticFunction();
MyClass.staticVar;
MyClass.STATIC_CONST;
It is that easy! maybe not to intuitive for Java developers but still it is not so bad idea - I like it. Do you ?

Demony Przeszłości

Dziś dzięki uprzejmości mojej firmy Pragmatists uczestniczyłem w pierwszym dniu szkolenia "Zwinne Rozwijanie Oprogramowania", prowadzonego przez (nie bójmy się tego słowa) wybitnych praktyków/teoretyków zwinnych metodyk: Pawła Lipińskiego i Krzysztofa Jelskiego. Pomimo, że ze SCRUMem pracuję już ponad dwa lata a z XP 7 miesięcy,  to postanowiliśmy z Pawłem wysłać mnie na to szkolenie celem usystematyzowania mojej wiedzy.

Jako, że wśród uczestników szkolenia mało się znaliśmy (chociaż były również twarze znajome z WJUGa) zaczęliśmy od odpowiedzenia na kilka prostych pytań, między innymi  "czym się zajmuję". Moją szczególną uwagę zwrócił kolega Kamil, który powiedział coś w stylu: "właśnie skończyłem pracę nad kodem stworzonym przez Michała". Buzia mi się zaraz uśmiechnęła do wspomnień, bo domyślałem się o jaki projekt chodzi. Mój pierwszy, który współtworzyłem jako zawodowy programista. A wręcz mój pierwszy projekt który na miano projektu zasługiwał.

Kidy wróciłem do domu poruszyłem niebo i ziemię aby ten kod jakimś cudem zdobyć i udało się! To co zobaczyłem po otwarciu kodu źródłowego, przeszło moje najśmielsze oczekiwania.
To było jak podmuch wiatru znad morza, naszego polskiego morza... jak wiosenny ciepły deszcz na polskiej szlacheckiej wsi...
Ta przepiękna klasa ma ...1109 linii , 22 pola przeróżnych typów, 47 metod, wśród których są 130 linijkowe perełki. W każdej z nich oczywiście nie może zabraknąć zagnieżdżonych ifów w ifach, poprzeplatanych pętlami no i oczywiście obsługą wyjątków.  Aż mi się łezka w oku zakręciła jak popatrzyłem co za potwora stworzyłem.

Chyba powinienem sobie tę klasę wydrukować i powiesić na ścianie by była przestrogą abym nigdy więcej nie był ojcem takiego Frankensteina.

A Kamila, i wszystkich  innych którzy pracowali nad tym kodem, serdecznie przepraszam i współczuję. Mogę tylko zapewnić, że od tego czasu w moim warsztacie programistycznym bardzo wiele się zmieniło, i taka sytuacja nigdy więcej się nie powtórzy.

...
...
Przysięgam!

piątek, 3 lipca 2009

Beauty and the beast: JavaFX 1.2 in Netbeans Platform 6.7

During last 2 months my and my colleagues from my company were developing application in JavaFX. During this time we have created same really nice working and looking components:
  • Interactive and animating graph with zooming functionality,
  • Editable label with noticing that text inside it was changed external,
  • table containing those editable label (JavaFX itself or any external libraries does not contains table component).

Of course we had some hard time with JavaFX as it is really young technology, but still we loved how easily we could create effectively looking and working components. Not mentioning BIND functionality which is one of the things that JavaFX developers will fall in love from the first sight :)

But a week ago our customer decided that he needs pluginable envierment and almous every element in the system needs to be a separate plugin. In the begining I was crushed. I thought that one month of our hard work will go to trash.

"We can put our JavaFX components into swing application, I've seen examples on the internet" - said my manager. So I've started looking for it and I have found not really nice looking hack called JFXScene (http://blogs.sun.com/javafx/entry/how_to_use_javafx_in), but also in comments to that article I've found info that this hack is not working with in JavaFX 1.2. But my manager said that for sure this is possible and he will do it even so google does not know it :) And he did :) How ? It is really simple, a lot simpler then a hack described in mentioned link. In few sections I will try to explain how to put JavaFX components into swing application and then into Netbeans Platform.

1. Let's start!

First we need some JavaFX component that we will try to put into swing application. Lets create our own button
public class NiceLookingButton extends CustomNode, JFXScene{
  var color = Color.LIGHTGRAY;
  var button:Rectangle;

  override function create():Node{
    var text = Text{
      content:"Button"
      fill: Color.WHITE
      font: Font{
        size: 20
      }
    }

    button = Rectangle{
      x: 0 y: 0
      width: 100 height: 50
      arcHeight:10 arcWidth: 10
      strokeWidth: 3
      stroke: bind color
      fill: LinearGradient{
        startX: 0 endX: 0
        startY: 0 endY: 1
        stops: [
          Stop{ color: Color.WHITE offset: 0},
          Stop{ color: color offset: 0.3}
        ]
      }
      onMouseEntered: function(event){
        color = Color.LIGHTBLUE;
        setFill();
      }
      onMouseExited: function(event){
        color = Color.LIGHTGRAY;
        setFill();
      }
}
    Stack{
      effect: Reflection{}
      content:[
        button,
        text
      ]
    } 
function setFill(){
    button.fill = LinearGradient{
      startX: 0 endX: 0
      startY: 0 endY: 1
      stops: [
        Stop{ color: Color.WHITE offset: 0},
        Stop{ color: color offset: 0.3}
      ]
    }
  }

}


2. Prepare to swing.


Now, when we have really pretty :) JavaFX component we can prepare it for swinging. To do this first we need to create MIXIN class.
What is mixin? Mixin was added in JavaFX 1.2 and it is a special type of class, it can not be constructed but other classes can implement multiple inheritance with them. In other words normal classes can extends many mixin classes.

Our mixin implements method that puts component into JavaFX Scene and in the end gets Object that extends JComponent.
public mixin class JFXScene {
  public function getScene():JComponent{
    var scene = Scene{content: this as Node};
    var swingScene = scene.impl_getPeer() as SwingScene;
    return swingScene.scenePanel;
  }
}

Now we can change implementation of NiceLookingButton:

public class NiceLookingButton extends CustomNode, JFXScene {
  //no changes here
}


The last thing we have to do is to add JavaFX 1.2 run time library ( which can be download from here : http://dl.javafx.com/javafx-rt-windows-i586__V1.2.0_b233.jar ) to our project class path.

Is it all? YES! it is THAT simple! we are now ready to put JavaFX component into normal Swing application!

3. Lets SWING!

Now we can create Simple Swing application, and put on its classpath javafx-rt downloaded in previous section and jar file with our JavaFX Component.

public class MainFrame extends javax.swing.JFrame {
  public MainFrame() {
    initComponents();
  }

  private void initComponents() {
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(new NiceLookingButton().getScene());
    pack();
  }

  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        new MainFrame().setVisible(true);
      }
    });
  }
}


As you can see in the code we do not use any hack or reflection to create our button, we just use normal no-argument constructor like we would create every other Java class. Isn't this nice?

Since in swing application we have references to NiceLookingButton we can invoke any public methods like on any other java object.

3. "New construction options"

If you have worked with JavaFX before you probably know that in JavaFX Scirpt you do not declare any constructors, you create object in very nice "groovy-like" way:
MyJavaFXObject{firstName: "Michal", surename: "Margiel"  }
As you can see it is really nice, but it determines that in classes compiled from JavaFX Script ces we have only default, no-argument constructor. But what if we would like to pass some information during object construction? Well... No problem ! we just need to introduce static factory method.

Since there is no static key word in JavaFX all static members are declared like any other but outside class.
So if we would like to pass i.e. width and height of the button we need to introduce those properties as public variables and introduce this method:

public function create(width:Integer, height:Integer):NiceLookingButton{
  NiceLookingButton{width: width, height: height}
}

public class NiceLookingButton extends CustomNode, JFXScene{
  (...)
}



Now we just need to rebuild our library and from now on we can invoke our factory method.

private void initComponents() {
  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  getContentPane().setLayout(new FlowLayout());
  NiceLookingButton button = NiceLookingButton.create(200, 100);
  getContentPane().add(button.getScene());
  pack();
}


4. Push the Button

Ok, So we can construct JavaFX objects with parameters and put them into Swing applications, also we know that we can invoke all public methods on them. But our component is a Button so it should be able react on clicking on it on swing side. Can we do it? Again - YES!

We need to introduce public variable with type function() inside NiceLookingButton
public class NiceLookingButton extends CustomNode, JFXScene{
  public var width:Integer = 100;
  public var height:Integer = 50;
  public var onMouseClick:function();
  (...)
}

and then invoke it when user click on our button (Rectangle)
onMouseClicked: function(event){
  onMouseClick();
}

after rebuilding library we have access to $onMouseClick property which accepts Function0 . Function0 is an interface with method

public Void invoke()

which will be invoke when user will click our button. Lets introduce simple implementation:

button.$onMouseClick = new Function0(){
  public Void invoke() {
    System.out.println("Nice Looking JavaFX Button Clicked!");
    return null;
  }
};

As you might noticed invoke method returns Void Object so we have to return at least null;



5. JavaFX Platform?

Ok, so the question for now is: Since NetBeans Platform uses Swing, can we also use JavaFX inside it?
and the answer is of course - YES :) and it is again really, really simple!
We just have to fallow few steps:
  1. Wrap up jar containing NiceLookingButton and javafx-rt into Netbeans Platform Modules.
  2. Add javafx-rt module to yourJavaFXLibrary module.
  3. Create Netbeans Platform Module with Window Component and add both yourJavaFXlibrary and javafx-rt module.
  4. Add NiceLookingButton to your TopComponent,
  5. private void initComponents() {
      setLayout(new FlowLayout());
      NiceLookingButton button = NiceLookingButton.create(200, 100);
      button.$onMouseClick = new Function0(){
        public Void invoke() {
          System.out.println("Nice Looking JavaFX Button Clicked!");
          return null;
        }
      };
      add(button.getScene());
    }
    
  6. Run NetBeans Platform project, and voilà!
We can see our button in Netbeans Platform, and all actions (like hovering and clicking) still works!

6. Yes, Yes, Yes!

So conclusion is really great!.
  • Yes! - you can use your JavaFX 1.2 components without any reflection inside Swing applications.
  • Yes! - you can invoke methods on javaFX components from swinf and oposite
  • and Yes! - you can use JavaFX in Netbeans Platform to build JavaFX Platform :)
(from left JavaFX app, Swing app with JavaFX component, and NetBeans Platform with JavaFX component)

All three NetBeans projects (JavaFX, Swing and NetBeans Platform) are available here.
In case of any questions just write to me!

wtorek, 10 marca 2009

Blogi, groovy, java i String

Od jakiegoś czasu rozpoznaje webowe dziecko Grooviego czyli Grails. Jest to świetny framework do małych aplikacyjek, którego polecam wszystkim.

Aby dowiedzieć się czegoś ciekawego o Grailsach wszedłem odwiedziłem również bloga Radka Holewy - jednego z liderów PLJUGa. Tam znalazłem bardzo ciekawy wpis "Groovy - przydatne informacje" który zawiera zestaw "sznurków" przydatnych dla każdego zainteresowanego językiem groovy. jednym z linków był Grails Tutorials, a stamtąd już prosto na bloga 3.times { theFun } i post Syntactic Sugar. Opisana jest w nim uproszczona składnia pętli for w groovim, lecz to co co przyciągnęło moja uwagę to komentarz autora o "syntactic sugar" w Javie. A konkretnie o klasie String tworzeniu jej obiektów.


In Java we can create a String through the object model by calling a constructor:

String name = new String ("eduardo");

Or we can use this bit of "syntactic sugar":

String name = "eduardo";

As you can see, syntactic sugar gives us two things: clarity and conciseness. It does not add any new functionality

Czemu mnie ten fragment zaciekawił? Powód jest prosty... autor dość znacznie mija się z prawdą. Różnica pomiedzy new String("tekst") oraz "tekst" jest dość duża. Ta pierwsza konstrukcja ZAWSZE tworzy nowego string, a ta druga najpierw wyszukuje czy już taki łańcuch istnieje w puli, jeśli tak to podpina się pod niego, a jeśli nie to tworzy nowy i wrzuca go do puli. Można by więc powiedzieć, że niejawnie wywołuje metodę intern(). Z tych powodów jawnego konstruktora klasy String NIGDY nie powinno sie uzywać. Jak widać nie jest to więc tylko syntactic sugar i jak najbardziej dodaje nową funkcjonalność.

Opisałem więc cała sprawę w komentarzy do posta, jednakże gdy kliknąłem "Post Comment" okazało się, że musi być on zaakceptowany przez bloggera. Niestety nie wszyscy potrafią przyjąć krytykę więc mój komentarz się nie pojawił, natomiast post stał się bogatszy o jedno słowo.

I tak zdanie

"It does not add any new functionality"

zostało zmienione na

"It USUALY does not add any new functionality"


Powiem szczerze, że przykra jest dla mnie taka cenzura na blogach... no ale jak to mawiał Ryszard Ochódzki "trudno... co zrobić"

niedziela, 1 lutego 2009

NetBeans 6.5 i skróty klawiszowe - bo w życiu nie może być za łatwo...

Występ Adama Biena, niemieckiego Java Chempiona, był moim zdaniem jednym z najjaśniejszych punktów ubiegłorocznego JDD. Tezy które wypowiadał były jakby wprost wyjęte z mojej głowy - krytyka nadmiernego rozwarstwienia aplikacji, niezrozumiałe ogromne podniecanie się Springiem i jeszcze bardziej nie zrozumiała i jeszcze bardziej ogromna krytyka EJB 3.0 . Rozłożył mnie na łopatki swoją energią i poczuciem humoru. Wręcz nazwałem go niemieckim Jackiem Laskowskim :) Od tego czasu jestem stałym (chodź nie regularnym) czytelnikiem bloga Adama (nie jesteśmy na Ty ale mam nadzieje, że nikt się nie obrazi za moją nadmierną poufałość ).

Dość pokaźna część postów na tym blogu (90% ?) poświęcona jest najnowszej odsłonie IDE od Suna, czyli NetBeans 6.5. Jako, że jestem wręcz fanatycznym fanem nowych technologii i uwielbiam poznawać wszystko co nowe i "fajne" postanowiłem wypróbować to najmłodsze dziecko programistów  z Pragi. A że zacząłem również poznawać Apache Wicket, postanowiłem upiec dwie pieczenie na jednym ogniu i programować Wicketa właśnie w NetBeans.

Jak już pisałem w postach o Eclipse, podczas poznawania nowego edytora pierwsze co robię to wchodzę w ustawienia kluczy klawiszowych by sprawdzić czy to środowisku udostępnia moje ulubione operacje. I tu pierwszy zawód... Wciąż programiści Sun'a nie wprowadzili tak banalnej funkcjonalności jak wyszukiwanie skrótów. Czemu tego nie zrobili od tak wielu edycji jest dla mnie czymś czego nigdy nie zrozumiem.  

"Lecz nie jest tak źle!" - można by pomyśleć. Gdyż skróty pogrupowane są w miarę sensowne kategorie...


Ja potrzebowałem skrótu który usuwał linię w której aktualnie znajduje się kursor (eclipse -> ctrl+d). Kierując się moja pokrętną logiką sądziłem, że skrót ten znajdzie się w kategorii "edit" lub "source".

 Ale najwyraźniej myślenie tego dnia nie szło mi najlepiej gdyż skrót ten odnalazłem dopiero w sekcji... i tu uwaga... "OTHERS". Logiczna prawda? :D

Niby to wszystko drobnostki, ale muszę przyznać ze zniechęcają mnie do tego środowiska... Mam nadzieje, że dalej będzie już tylko lepiej.

A skrótu do zduplikowania linii wciąż poszukuje.