Multimedia‎ > ‎

Display Images


JavaFX makes it easy to load and display images located locally or remotely using the Image API.  The API offers two classes, Image and ImageView that work together to load and display the image respectively.  The following code segment shows how to pull an image from Flickr and display it in an application:

def w = 800;
def h = 600;
var scene:Scene;
def maxW = w * 0.9;
def maxH = h * 0.9;

def imgView:ImageView = ImageView{
    preserveRatio:true
    fitWidth: maxW
    fitHeight:maxH
    layoutX:(w-maxW)/2 layoutY:(h-maxH)/2
};

function loadImg(){
    imgView.image = Image{
        url:(scene.lookup("addr") as TextBox).text
        backgroundLoading:true
    }
}

def addrBar = Group{
    layoutX: 20
    layoutY: 20
    content:HBox {
        nodeVPos:VPos.CENTER
        spacing:7
        content:[
            Label{text:"Image URL:" textFill:Color.SILVER}
            TextBox{id:"addr" columns:80 promptText:"http://"
                action:function(){loadImg()}
            }
            Button{id:"btnGo" text:"Get Image"
                action:function(){loadImg()}
            }
        ]
    }
}

Stage {
title : "Image Browser"
scene: scene = Scene {
                fill:Color.BLACK
width: w
height: h
content: [imgView, addrBar ]
}
}

When you compile and run the code above, you get an image-browser as shown below.  Enter the URL of an image from Flickr, for instance,  and press the "Get Image" button.


The materials on this website represent a small sample of content loosely based on the book JavaFX Application Development Cookbook.  The book offers far more content with over 80 recipes covering a range of topics from basics to advanced concepts.  

Buy the Book

You can get your copy of the book directly from the publisher. Click here to order!