How to use a Glade UI (.glade file) in a Java Gnome/GTK program?

折月煮酒 提交于 2019-12-05 16:55:29

Ok, you need to:

  • Init GTK library
  • Create a Builder object
  • Retrieve the window widget
  • Display the window widget

I assume you have already installed the java-gnome library in your Linux system and imported the jar in your eclipse project (project properties - java build path - add external jars - /usr/share/java/gtk.jar).

A sample code:

Gtk.init(args); //Init library
Builder b = new Builder();  //Create builder
b.addFromFile("filename.glade");  //Load layout from file
Window w = (Window) b.getObject("myWindowName");  //Retrieve an object
w.showAll(); //Show window
Gtk.main();

This is the way it should work. If you want to set a listener on an object, e.g. a button, you retrieve the oject by name as seen before with the window and then:

button.connect(new Clicked() {

    @Override
    public void onClicked(Button arg0) {
        // Do what you want
    }
});

Is it working for you? Well, it's not for me. The problem was my code was throwing an exception when calling Builder.addFromFile(filename)

java.text.ParseException: Invalid object type `GtkLabel'

The error is about the first element in the tree. After a deep research I found that, due to a known bug never fixed, you need to pre-define every widget before using it: in this case just call

 new Label();

before creating the builder.

This is, obviously, not intended to work in this way, and will be fixed in the future.

More info on this issue:

Thread on java-gnome-developer mailing list

Thread on Java-gnome-hackers mailing list

Hope this can help...

You're supposed to use the Builder class (available since java-gnome 4.0.20). Create it, call the addFromFile method to give it your glade file. Then just call getObject with the name of the object as entered in the Glade UI to get that object. The only thing I see as missing is the signal connection stuff. The original GtkBuilder class (in C) provides much more, especially signals connection features (gtk_builder_connect_signals for example). So you may need to connect signals by hand if these features are not available in the Java bindings. This means setting in glade in the "signals" tab the signal you want to connect, and setting the name of the callback this signal will call. You can have a good guess of the basics by seeing how it's done in python:

http://python-gtk-3-tutorial.readthedocs.org/en/latest/builder.html

Just browse the web for "glade tutorial" or "glade gtkbuilder" for the rest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!