RadioButton (JavaScript) Taryn Fox jewelfox@fursona.net 2012 Sólo se puede seleccionar uno a la vez Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 RadioButton

Los botones de radio se llaman así por las radios de los coches viejos, que tenían botones para alternar entre canales programados. Dado que la radio sólo podía sintonizar una estación a la vez, sólo se podía apretar un botón por vez; si presionaba uno nuevo, el que ya estaba presionado saltaba. Así es como estos botones funcionan.

Cada botón de radio necesita una etiqueta de texto y un grupo. Sólo se puede seleccionar un botón de cada grupo por vez. No necesita nombrar cada grupo; sólo configure varios botones de radio para que sean parte del mismo grupo que otro existente. Si crea uno nuevo fuera de un grupo, automáticamente crea un grupo nuevo para que forme parte.

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 RadioButtonExample = new Lang.Class({ Name: 'RadioButton Example', // Create the application itself _init: function() { this.application = new Gtk.Application({ application_id: 'org.example.jsradiobutton', 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 window when active _onActivate: function() { this._window.present(); }, // Callback function for 'startup' signal builds the UI _onStartup: function() { this._buildUI (); },

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

// Build the application's UI _buildUI: function() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, border_width: 20, title: "Travel Planning"});

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.

Crear los botones de radio // Create a label for the first group of buttons this._placeLabel = new Gtk.Label ({label: "Where would you like to travel to?"});

Se usa una Gtk.Label para diferenciar cada grupo de botones de radio. Nada le impedirá poner botones de radio de grupos diferentes donde quiera, así que si quiere que la gente sepa cuáles van juntos, necesita ordenar las cosas adecuadamente.

// Create three radio buttons three different ways this._place1 = new Gtk.RadioButton ({label: "The Beach"}); this._place2 = Gtk.RadioButton.new_from_widget (this._place1); this._place2.set_label ("The Moon"); this._place3 = Gtk.RadioButton.new_with_label_from_widget (this._place1, "Antarctica"); // this._place3.set_active (true);

Aquí hay tres maneras diferentes de crear botones de radio. La primera es la manera común, donde se crea un «Gtk.RadioButton» nuevo y se le asignan sus propiedades al mismo tiempo. La segunda y la tercera usan funciones que manejan algunas de sus propiedades automáticamente; «new_from_widget» toma un solo argumento, un botón de radio del mismo grupo en el que quiere poner el nuevo. «new_with_label_from_widget», además, toma eso y la etiqueta del botón de radio al mismo tiempo.

El primer botón de radio en un grupo es el que está seleccionado de manera predeterminada. Pruebe a descomentar la última línea en este código de ejemplo para ver cómo puede configurar uno diferente para que sea la selección predeterminada.

// Create a label for the second group of buttons this._thingLabel = new Gtk.Label ({label: "And what would you like to bring?" }); // Create three more radio buttons this._thing1 = new Gtk.RadioButton ({label: "Penguins" }); this._thing2 = new Gtk.RadioButton ({label: "Sunscreen", group: this._thing1 }); this._thing3 = new Gtk.RadioButton ({label: "A spacesuit", group: this._thing1 });

Aquí se crea la etiqueta para el segundo grupo de botones, y después se crean todos de la misma manera.

Crear el resto de la interfaz de usuario // Create a stock OK button this._okButton = new Gtk.Button ({ label: 'gtk-ok', use_stock: 'true', halign: Gtk.Align.END }); // Connect the button to the function which handles clicking it this._okButton.connect ('clicked', Lang.bind (this, this._okClicked));

Este código crea un Gtk.Button y lo enlaza a una función que mostrará un mensaje tonto cuando pulse «OK», dependiendo de qué botones de radio se seleccionaron.

Para asegurarse de que la etiqueta «OK» del botón se muestra correctamente en cada idioma al que se traduce GNOME, recuerde usar uno de los tipos de botón del almacén de GTK+.

// Create a grid to put the "place" items in this._places = new Gtk.Grid (); // Attach the "place" items to the grid this._places.attach (this._placeLabel, 0, 0, 1, 1); this._places.attach (this._place1, 0, 1, 1, 1); this._places.attach (this._place2, 0, 2, 1, 1); this._places.attach (this._place3, 0, 3, 1, 1); // Create a grid to put the "thing" items in this._things = new Gtk.Grid ({ margin_top: 50 }); // Attach the "thing" items to the grid this._things.attach (this._thingLabel, 0, 0, 1, 1); this._things.attach (this._thing1, 0, 1, 1, 1); this._things.attach (this._thing2, 0, 2, 1, 1); this._things.attach (this._thing3, 0, 3, 1, 1); // Create a grid to put everything in this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, margin_left: 40, margin_right: 50 }); // Attach everything to the grid this._grid.attach (this._places, 0, 0, 1, 1); this._grid.attach (this._things, 0, 1, 1, 1); this._grid.attach (this._okButton, 0, 2, 1, 1); // Add the grid to the window this._window.add (this._grid);

Se usa una Gtk.Grid separada para organizar cada grupo de botones de radio. De esta manera se puede cambiar la distribución sin liarse más adelante. La segunda rejilla tiene un margen en la parte superior, para separar visualmente los dos conjuntos de opciones.

Después de haberlos organizado, se ponen en una tercera rejilla maestra, junto con el botón «OK». Luego se adjuntan a la ventana.

// Show the window and all child widgets this._window.show_all(); },

Finalmente, se le dice a la ventana y a todo dentro que se vuelva visible cuando se ejecute la aplicación.

Función que maneja su selección _okClicked: function () { // Create a popup that shows a silly message this._travel = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, message_type: Gtk.MessageType.OTHER, buttons: Gtk.ButtonsType.OK, text: this._messageText() }); // Show the popup this._travel.show(); // Bind the OK button to the function that closes the popup this._travel.connect ("response", Lang.bind (this, this._clearTravelPopUp)); },

Cuando pulsa «OK», aparece un Gtk.MessageDialog. Esta función crea y muestra la ventana emergente, después enlaza su botón «OK» a una función que la cierra. Qué texto aparece en el mensaje emergente depende de la función «_messageText()», que devuelve un valor diferente dependiendo de qué conjunto de opciones elija.

_messageText: function() { // Create a silly message for the popup depending on what you selected var stringMessage = ""; if (this._place1.get_active()) { if (this._thing1.get_active()) stringMessage = "Penguins love the beach, too!"; else if (this._thing2.get_active()) stringMessage = "Make sure to put on that sunscreen!"; else stringMessage = "Are you going to the beach in space?"; } else if (this._place2.get_active()) { if (this._thing1.get_active()) stringMessage = "The penguins will take over the moon!"; else if (this._thing2.get_active()) stringMessage = "A lack of sunscreen will be the least of your problems!"; else stringMessage = "You'll probably want a spaceship, too!"; } else if (this._place3.get_active()) { if (this._thing1.get_active()) stringMessage = "The penguins will be happy to be back home!"; else if (this._thing2.get_active()) stringMessage = "Antarctic sunbathing may be hazardous to your health!"; else stringMessage = "Try bringing a parka instead!"; } return stringMessage; },

El método «get_active()» indica qué botón de radio está presionado. Esta función devuelve un mensaje tonto diferente dependiendo de qué conjunto de botones se presionó. Su valor de retorno se usa como propiedad «text» del «MessageDialog».

_clearTravelPopUp: function () { this._travel.destroy(); } });

Esta función se llama cuando se presiona el botón «OK» del «MessageDialog». Simplemente hace desaparecer el diálogo emergente.

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

Finalmente, se crea una instancia nueva de la clase RadioButtonExample 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 RadioButtonExample { // Create the application itself constructor() { this.application = new Gtk.Application({ application_id: 'org.example.jsradiobutton', 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 window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { 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, border_width: 20, title: "Travel Planning"}); // Create a label for the first group of buttons this._placeLabel = new Gtk.Label ({label: "Where would you like to travel to?"}); // Create three radio buttons three different ways this._place1 = new Gtk.RadioButton ({label: "The Beach"}); this._place2 = Gtk.RadioButton.new_from_widget (this._place1); this._place2.set_label ("The Moon"); this._place3 = Gtk.RadioButton.new_with_label_from_widget (this._place1, "Antarctica"); // this._place3.set_active (true); // Create a label for the second group of buttons this._thingLabel = new Gtk.Label ({label: "And what would you like to bring?" }); // Create three more radio buttons this._thing1 = new Gtk.RadioButton ({label: "Penguins" }); this._thing2 = new Gtk.RadioButton ({label: "Sunscreen", group: this._thing1 }); this._thing3 = new Gtk.RadioButton ({label: "A spacesuit", group: this._thing1 }); // Create a stock OK button this._okButton = new Gtk.Button ({ label: 'gtk-ok', use_stock: 'true', halign: Gtk.Align.END }); // Connect the button to the function which handles clicking it this._okButton.connect ('clicked', this._okClicked.bind(this)); // Create a grid to put the "place" items in this._places = new Gtk.Grid (); // Attach the "place" items to the grid this._places.attach (this._placeLabel, 0, 0, 1, 1); this._places.attach (this._place1, 0, 1, 1, 1); this._places.attach (this._place2, 0, 2, 1, 1); this._places.attach (this._place3, 0, 3, 1, 1); // Create a grid to put the "thing" items in this._things = new Gtk.Grid ({ margin_top: 50 }); // Attach the "thing" items to the grid this._things.attach (this._thingLabel, 0, 0, 1, 1); this._things.attach (this._thing1, 0, 1, 1, 1); this._things.attach (this._thing2, 0, 2, 1, 1); this._things.attach (this._thing3, 0, 3, 1, 1); // Create a grid to put everything in this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, margin_left: 40, margin_right: 50 }); // Attach everything to the grid this._grid.attach (this._places, 0, 0, 1, 1); this._grid.attach (this._things, 0, 1, 1, 1); this._grid.attach (this._okButton, 0, 2, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); } _okClicked() { // Create a popup that shows a silly message this._travel = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, message_type: Gtk.MessageType.OTHER, buttons: Gtk.ButtonsType.OK, text: this._messageText() }); // Show the popup this._travel.show(); // Bind the OK button to the function that closes the popup this._travel.connect ("response", this._clearTravelPopUp.bind(this)); } _messageText() { // Create a silly message for the popup depending on what you selected var stringMessage = ""; if (this._place1.get_active()) { if (this._thing1.get_active()) stringMessage = "Penguins love the beach, too!"; else if (this._thing2.get_active()) stringMessage = "Make sure to put on that sunscreen!"; else stringMessage = "Are you going to the beach in space?"; } else if (this._place2.get_active()) { if (this._thing1.get_active()) stringMessage = "The penguins will take over the moon!"; else if (this._thing2.get_active()) stringMessage = "A lack of sunscreen will be the least of your problems!"; else stringMessage = "You'll probably want a spaceship, too!"; } else if (this._place3.get_active()) { if (this._thing1.get_active()) stringMessage = "The penguins will be happy to be back home!"; else if (this._thing2.get_active()) stringMessage = "Antarctic sunbathing may be hazardous to your health!"; else stringMessage = "Try bringing a parka instead!"; } return stringMessage; } _clearTravelPopUp() { this._travel.destroy(); } }; // Run the application let app = new RadioButtonExample (); app.application.run (ARGV);
Documentación en profundidad

Gtk.Application

Gtk.ApplicationWindow

Gtk.Button

Gtk.Grid

Gtk.Label

Gtk.RadioButton