Pages

Tuesday, May 29, 2012

Java - Enumerated types

To enumerate some constant values, and/or associate to them methods or values, we can use enum in java. Enum types in Java are considered like classes, they can have constructors too, can implement interfaces, but can have no descendants. Let see, how we work with enum in java, through an example that classifies programming languages.
Create your own test class, and then test the following code:

    private enum prog_language {
        //enumerated constants
        java(true), c(true), basic(true), php(true), delphi(true), csharp(false), cplus(false);
       
        //fields to associate with the enum types
        private int position;
        private boolean usedbyme;
       
        //constructor
        prog_language(boolean bUsedByMe) {
            usedbyme = bUsedByMe;
        }           
        //getters and setters of the fields
        public int getPosition() {
            return position;
        }
        public void setPosition(int position) {
            this.position = position;
        }          
        public boolean isUsedbyme() {
            return usedbyme;
        }       
    };

.......................................       
        int i = 0;
        for (prog_language p : prog_language.values()) {
            i++;
            p.setPosition(i);
        }                              
        System.out.print(prog_language.valueOf("java").name());      
        System.out.println(" - at position: "+prog_language.valueOf("java").getPosition());
        System.out.println("I am using this language: "+prog_language.valueOf("java").isUsedbyme());

   
 
Enum types can also participate in switch-case statements too.

Thursday, May 24, 2012

Java - Data Structures

Data Structure       Advantages                Disadvantages



Array
Quick insertion
(very fast access if index known.)
Slow search, 
Slow deletion, 
fixed size.
Ordered Array
Quicker search
Slow insertion,
Slow deletion,
fixed size. 
Stack
Provides last-in, first-out access
Slow access to other items
Queue
Provides first-in, first-out access
Slow access to other items
Linked list
Quick insertion, quick deletion
Slow search
       ArrayList           
(is same as a Vector. Vectors are
synchronized, can be thread safe, but
slower)
Binary Search, Sort
Slow insertion, deletion
Binary tree
Quick insertion, deletion (if tree remains balanced), and search.
Deletion algorithm is complex
Red-black tree
Quick insertion, deletion (this tree is always balanced), and search.
Complex
2-3-4 tree
Quick insertion, deletion (this tree is always balanced, is good for disk storage progr.), and search.
Complex
Hash table (~arrays)
Very fast access if key known. Fast insertion
Slow deletion, access slow if key not known, inefficient memory usage.
Heap (~LinkedList)
Fast insertion, deletion, access to largest item.
Slow access to other items
Graph
Models real-world situations.
Slow and complex.
                       

Java - Maps / storing values in key-value pair

        Map<String, Integer> mPair = new HashMap<String, Integer>();       

        mPair.put("one", new Integer(1));
        mPair.put("two", new Integer(2));
        mPair.put("three", new Integer(3));
        System.out.println(mPair.values());

        if (mPair.containsKey("two"))
            System.out.println(mPair.get("two"));

Thursday, May 17, 2012

Vaadin - TextField componet, value change listener

Working with TextField component in Vaadin framework web environment, is much like, working with components in swing/awt applications. Here, we also have events and listeners.
For example, changing a value in a TextField componet, can be captured right after the field, loses focus.



Just have the following class and add to your Vaadin web application:

public class MyApplication extends Application {
    //global components
    TextField tfInput;
    Window mainWindow;
   
    //main method - init()
    @Override
    public void init() {
    mainWindow = new Window("MyApplication");
        tfInput = new TextField("Enter your Name: ");
        tfInput.setValue("empty");
       
        //handling the change of the texfield value property:
        tfInput.addListener(new Property.ValueChangeListener() {
            @Override
            public void valueChange(ValueChangeEvent event) {
                // Assuming that the value type is a String
                String value = (String) tfInput.getValue();               
                Window.Notification notif = new Window.Notification("Be warned "+value+"!",
                        "<br/>This message warning, after a field value change, stays centered, till you do sthg!",
                        Window.Notification.TYPE_WARNING_MESSAGE);
                notif.setPosition(Window.Notification.POSITION_CENTERED);
                mainWindow.showNotification(notif);
            }           
        });       
        // Fire value changes immediately when the field loses focus
        tfInput.setImmediate(true);       
               
    mainWindow.addComponent(tfInput);
    setMainWindow(mainWindow);
    }
}

The same thing you can achieve by binding the TextField component to an ObejectProperty value. The change of this ObjectProperty value, is immediately reflected anywhere.

public class MyApplication extends Application {
    Double trouble = 42.0;
    final ObjectProperty<Double> property = new ObjectProperty<Double>(trouble);
      
    @Override
    public void init() {
    Window mainWindow = new Window("MyApplication");
        TextField tf = new TextField("The Answer",property);
        tf.setImmediate(true);
       
        Label feedback = new Label(property);
        feedback.setCaption("The Value");
       
        Panel pnl = new Panel();
        pnl.addComponent(tf);
        pnl.addComponent(feedback);
       
    mainWindow.addComponent(pnl);
    setMainWindow(mainWindow);
    }
}

Just try it and test, this code on: http://lehelsipos.appspot.com/

Wednesday, May 16, 2012

Creating an embedded JavaDB with netbeans with a given path at your local hard disk

Using the Netbeans IDE it is very easy to create an embedded JavaDB database. Just follow the steps:
1. open your netbeans ide :)
2. go to services tab
3. open Databases then Drivers and right click the Java DB (Embedded)
4. after "connect using" in the jdbc url write the following:
jdbc:derby:c:/yourPath/DB/yourDb;create=true
Success.

Thursday, May 10, 2012

JavaFx - Button - showing a Message, styling and some effects.

A small code to present, how can we work with buttons in JavaFx:





package javafxapplication_button;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;

/**
 *
 * @author Sipos Lehel
 */
public class JavaFXApplication_Button extends Application {

    Button btn = null;
    DropShadow shadow = null;  
   
    public static void main(String[] args) {
        launch(args);
    }
   
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
       
       
        //button icon
        Image imageDecline = new Image(getClass().getResourceAsStream("desktop.gif"));
        btn = new Button("OK");
        btn.setGraphic(new ImageView(imageDecline));       
       
       
        //effects at mouse moving upon the button
        shadow = new DropShadow();
        //Adding the shadow when the mouse cursor is on and zooming in
        btn.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent e) {
                btn.setEffect(shadow);
                btn.setScaleX(1.5);
                btn.setScaleY(1.5);                
            }
        });
        //Removing the shadow when the mouse cursor is off and zooming out
        btn.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent e) {
                btn.setEffect(null);
                btn.setScaleX(1);
                btn.setScaleY(1);                                
            }
        });       
       
        //on click event - fire a Dialog Box message
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                Stage dialogStage = new Stage();
                dialogStage.initModality(Modality.WINDOW_MODAL);
                StackPane panel = new StackPane();
                panel.getChildren().add(new Text("This is a message for you: Hello world!"));
                Scene scene_message = new Scene(panel);
                dialogStage.setScene(scene_message);
                dialogStage.setHeight(100);
                dialogStage.setWidth(300);
                dialogStage.show();

            }
        });       
       
        //styling the button
        btn.setStyle("-fx-font: 22 arial; -fx-text-base-color: blue; -fx-base: #b6e7c9");       
       
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}





Wednesday, May 9, 2012

Vaadin - Form Data Saving into a second form

Add the following unit into your vaadin application (it runs under the lehel.sipos.vaadin package):

/*
 * MyApplication.java
 *
 * Created on 2012. május 9., 12:16
 */

package lehel.sipos.vaadin;          

import com.vaadin.Application;
import com.vaadin.data.Validator.EmptyValueException;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.data.util.PropertysetItem;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.Reindeer;
/**
 *
 * @author Sipos Lehel
 * @version
 */

public class MyApplication extends Application {

    @Override
    public void init() {
    Window mainWindow = new Window("MyApplication");
              
        // Some data source
        PropertysetItem item = new PropertysetItem();
        item.addItemProperty("firstName", new ObjectProperty<String>(""));
        item.addItemProperty("lastName",  new ObjectProperty<String>(""));
       
        // A buffered form bound to a data source - main form for input data
        final Form form = new Form();
        form.setItemDataSource(item);
        form.setWriteThrough(false);
       
        //caption of text fields in main form
        form.getField("firstName").setCaption("Keresztnév");
        form.getField("lastName").setCaption("Vezetéknév");       

        // A required field
        form.getField("firstName").setRequired(true);
       
        // A required field with an error message
        TextField lastName = (TextField) form.getField("lastName");
        lastName.setRequired(true);
        lastName.setRequiredError("Add meg a vezetéknevet");
        lastName.setImmediate(true);
        lastName.setValidationVisible(true);
        lastName.addValidator(new StringLengthValidator("Nem lehet üres", 1, 100, false));

        // Commit the buffered form data to the data source
        form.getFooter().addComponent(new Button("Mentés", new Button.ClickListener() {
            public void buttonClick(Button.ClickEvent event) {
                try {
                    if (!form.isValid())
                        form.setValidationVisible(true);
                    else
                        form.commit();
                } catch (EmptyValueException e) {
                    // A required value was missing
                }
            }
        }));

        // Have a read-only form that displays the content of the first form after a data commit
        Form roform = new Form();
        roform.setItemDataSource(item);       
        roform.addStyleName(Reindeer.LAYOUT_WHITE);       
        roform.setReadOnly(true);
        //caption of text fields in the readonly form form
        roform.getField("firstName").setCaption("Elmentett keresztnév");
        roform.getField("lastName").setCaption("Elmentett vezetéknév");       
       
       
       
        //putting the input form near the readonly form
        HorizontalLayout hlayout = new HorizontalLayout();
        hlayout.setSpacing(true);
        hlayout.setWidth("600px");
        hlayout.addComponent(form);
        hlayout.addComponent(roform);       
       
        mainWindow.addComponent(hlayout);
        setMainWindow(mainWindow);
    }

}

Tuesday, May 8, 2012

Vaadin

Vaadin is a web application framework for Rich Internet Applications (RIA). In contrast to Javascript libraries and browser-plugin based solutions, it features a robust server-side architecture. This means that the largest part of the application logic runs securely on the server. Google Web Toolkit (GWT) is used on the browser side to ensure a rich and fluent user experience.

JavaFX

JavaFX is the next step in the evolution of Java as a rich client platform. It is designed to provide a lightweight, hardware-accelerated Java UI platform for enterprise business applications. With JavaFX, developers can preserve existing investments by reusing Java libraries in their applications. They can even access native system capabilities, or seamlessly connect to server-based middleware applications.