MessageDialog (JavaScript) Taryn Fox jewelfox@fursona.net 2012 Una mensaje emergente acoplado a una ventana Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 MessageDialog

Un «MessageDialog» es un diálogo de mensaje modal, es decir un diálogo emergente al que tiene que responder antes de volver a lo que estaba haciendo en la ventana a la que está vinculado. Este puede hacer que el mundo explote (o al menos eso dice). Para hacer que el diálogo aparezca cuando ejecute este ejemplo, pulse «Message» dentro de su menú de aplicación (el que aparece cuando pulsa en el nombre de la aplicación en la esquina superior izquierda, junto a «Actividades»).

La diferencia entre un «MessageDialog» y un Dialog es que un «Dialog» puede contener cualquier widget y tener el contenido que quiera, mientras que un «MessageDialog» es sólo una manera cómoda de hacer que aparezca un diálogo emergente con un mensaje básico y botones.

Bibliotecas que importar #!/usr/bin/gjs const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Lang = imports.lang;

Estas son las bibliotecas que necesita importar para que esta aplicación se ejecute. Recuerde que la línea que le dice a GNOME que está usando Gjs siempre tiene que ir al principio.

Crear la ventana de la aplicación const MessageDialogExample = new Lang.Class ({ Name: 'MessageDialog Example', // Create the application itself _init: function () { this.application = new Gtk.Application ({ application_id: 'org.example.jsmessagedialog', flags: Gio.ApplicationFlags.FLAGS_NONE }); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', Lang.bind(this, this._onActivate)); this.application.connect('startup', Lang.bind(this, this._onStartup)); }, // Callback function for 'activate' signal presents windows when active _onActivate: function () { this._window.present (); }, // Callback function for 'startup' signal initializes menus and builds the UI _onStartup: function () { this._initMenus(); this._buildUI (); },

Todo el código de este ejemplo va en la clase «MessageDialogExample». El código anterior crea una Gtk.Application para que vayan los widgets y la ventana.

Antes de llamar a «_buildUI» para crear la ventana y sus widgets, es necesario llamar a «_initMenus», que le dice a GNOME que cree el menú. Se puede poner el código de «_initMenus» después del código de «_buildUI», dado que no importa en qué orden se esté mientras que «_initMenus» se llame primero en «_onStartup».

// Build the application's UI _buildUI: function () { // Create the application window this._window = new Gtk.ApplicationWindow ({ application: this.application, window_position: Gtk.WindowPosition.CENTER, title: "Gtk.MessageDialog Example", default_height: 200, default_width: 400 });

La función _buildUI es donde se pone todo el código que crea la interfaz de usuario de la aplicación. El primer paso es crear una Gtk.ApplicationWindow nueva para poner dentro todos los widgets.

// Create a silly warning message and add it to the window this.warningLabel = new Gtk.Label ({ label: "This application goes boom! (Not really.)"}); this._window.add (this.warningLabel);

Para este ejemplo, todo lo que hay en la ventana de la que viene el diálogo emergente es una Label de advertencia tonta.

Crear el «MessageDialog» _showMessageDialog: function () { // Create a modal MessageDialog whose parent is the window this._messageDialog = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, buttons: Gtk.ButtonsType.OK_CANCEL, message_type: Gtk.MessageType.WARNING, text: "This action will cause the universe to stop existing." }); this._messageDialog.connect ('response', Lang.bind(this, this._response_cb)); this._messageDialog.show(); },

Para hacer del «MessageDialog» un diálogo emergente vinculado a la ventana principal, se establece su propiedad «modal» a «true» y «transient_for» a «_window». Después, se puede configurar el tipo de botones que tiene y qué tipo de mensaje es (determinando el icono junto al mensaje), y escribir su texto, antes de conectar su señal «response» a la función de retorno de llamada que la maneja.

Aquí hay algunos recursos para hacer sus propios «MessageDialog»:

Lista de tipos de botones

Lista de tipos de mensajes

// Callback function (aka signal handler) for the response signal _response_cb: function (messagedialog, response_id) { // A simple switch that changes the main window's label switch (response_id) { case Gtk.ResponseType.OK: this.warningLabel.set_label ("*BOOM*\n"); break; case Gtk.ResponseType.CANCEL: this.warningLabel.set_label ("Good choice!\n"); break; case Gtk.ResponseType.DELETE_EVENT: this.warningLabel.set_label ("Dialog closed or cancelled.\n"); break; } this._messageDialog.destroy(); } });

Esta función toma dos parámetros, el «MessageDialog» y su «response_id», ambos proporcionados automáticamente (no tiene que pasarlos manualmente para que funcione). Aquí se usa un interruptor simple para cambiar el texto de la «etiqueta de advertencia», dependiendo de qué opción elija. «DELETE_EVENT» ocurre su presiona «Escape» para cancelar el «MessageDialog», en lugar de presionar «OK» o «Cancel». Elija lo que elija, el diálogo emergente de destruirá a continuación.

// Run the application let app = new MessageDialogExample (); app.application.run (ARGV);

Finalmente, se crea una instancia nueva de la clase «MessageDialogExample» terminada, y se ejecuta la aplicación.

Código de ejemplo completo #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; class MessageDialogExample { // Create the application itself constructor() { this.application = new Gtk.Application({ application_id: 'org.example.jsmessagedialog', flags: Gio.ApplicationFlags.FLAGS_NONE }); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents windows when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal initializes menus and builds the UI _onStartup() { this._initMenus(); this._buildUI (); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, title: "Gtk.MessageDialog Example", default_height: 200, default_width: 400 }); // Create a silly warning message and add it to the window this.warningLabel = new Gtk.Label({ label: "This application goes boom! (Not really.)" }); this._window.add (this.warningLabel); // Show the window and all child widgets this._window.show_all(); } // Build the application menu, including the button that calls the dialog _initMenus() { let menu = new Gio.Menu(); menu.append("Message",'app.message'); menu.append("Quit",'app.quit'); this.application.set_app_menu(menu); // This pops up a MessageDialog when "Message" is clicked in the menu let messageAction = new Gio.SimpleAction ({ name: 'message' }); messageAction.connect('activate', () => { this._showMessageDialog(); }); this.application.add_action(messageAction); // This closes the window when "Quit" is clicked in the menu let quitAction = new Gio.SimpleAction ({ name: 'quit' }); quitAction.connect('activate', () => { this._window.destroy(); }); this.application.add_action(quitAction); } _showMessageDialog() { // Create a modal MessageDialog whose parent is the window this._messageDialog = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, buttons: Gtk.ButtonsType.OK_CANCEL, message_type: Gtk.MessageType.WARNING, text: "This action will cause the universe to stop existing." }); this._messageDialog.connect ('response', this._response_cb.bind(this)); this._messageDialog.show(); } // Callback function (aka signal handler) for the response signal _response_cb(messagedialog, response_id) { // A simple switch that changes the main window's label switch (response_id) { case Gtk.ResponseType.OK: this.warningLabel.set_label ("*BOOM*\n"); break; case Gtk.ResponseType.CANCEL: this.warningLabel.set_label ("Good choice!\n"); break; case Gtk.ResponseType.DELETE_EVENT: this.warningLabel.set_label ("Dialog closed or cancelled.\n"); break; } this._messageDialog.destroy(); } }; // Run the application let app = new MessageDialogExample (); app.application.run (ARGV);
Documentación en profundidad

En este ejemplo se usa lo siguiente:

GMenu

GSimpleAction

Gtk.Application

Gtk.ApplicationWindow

Gtk.MessageDialog