“Hello World” example in Vala using Gtk+3

screenshot of gtk3 based vala example
Today I decided to rewrite a simple code of the “Hello World” example written in python by Micah Carrick almost a year ago. And I decided to do it in Vala! Vala has a modern syntax, compared to C# or java and brings many useful object oriented features. Vala’s compiler named “valac” translates your written code and based on it generates a C output, which it then compiles. I frequently observed how this project emerges, because I was fascinated by this idea from the beginning and soon realized, that I like to write in Vala myself too. Especially as I saw that the quadrapassel’s game code (a tetrix derivate in GNOME) was moved from C++ to Vala. So, here is a code of “hello_world.vala”:

namespace TestingWorld {
	class HelloWorld : Gtk.Application {
		public HelloWorld( ) {
			Object( application_id: "testing.hello.world",
					flags: ApplicationFlags.FLAGS_NONE );
		}
		
		public override void activate( ) {
			var window = new Gtk.Window( );
			window.set_title( "Gtk3 Vala Example" );
			window.set_default_size( 250, -1 );
			window.set_border_width( 24 );
			window.destroy.connect( () => { Gtk.main_quit( ); } );

			var label = new Gtk.Label( "Hello World!\nМиру Мир!" );
			window.add( label );
			window.show_all( );
			this.add_window( window );
		}

		public static void main( string[] args ) {
			var app = new HelloWorld( );
			app.run( );
		}
	}
}

This tiny example can be easily compiled with:

valac hello_world.vala --pkg gtk+-3.0 

Here, the created class “HelloWorld” is inherited from the Gtk.Application, which should replace the libunique functionallity. By providing a “application_id”, all the later launched instances join the same main loop. So, once you destroy it with “Gtk.main_quit”, all running application instances will be terminated. The “Gtk.Application”, additionally, provides many more usefull features, such as communication between running application instances.
If you do not like to write “Gtk.” every time when referring to classes from the GTK+ library, you can insert

 using Gtk;

at the beginning of the file. By doing so, you can omit the need of specifying the work space from where the classes you would like to use comes from. For example, you can then just write for the line number 15 the following:

 var label = new Label( "Hello World!" );

Why can’t I chain up to base constructor?

Advertisements

One thought on ““Hello World” example in Vala using Gtk+3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s