Blob Blame History Raw
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:xi="http://www.w3.org/2001/XInclude" type="guide" style="task" id="comboboxtext.js" xml:lang="es">
  <info>
  <title type="text">ComboBoxText (JavaScript)</title>
    <link type="guide" xref="beginner.js#menu-combo-toolbar"/>
    <link type="seealso" xref="GtkApplicationWindow.js"/>
    <link type="seealso" xref="messagedialog.js"/>
    <revision version="0.1" date="2012-07-06" status="draft"/>

    <credit type="author copyright">
      <name>Taryn Fox</name>
      <email its:translate="no">jewelfox@fursona.net</email>
      <years>2012</years>
    </credit>

    <desc>Un menú desplegable de solo texto</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Daniel Mustieles</mal:name>
      <mal:email>daniel.mustieles@gmail.com</mal:email>
      <mal:years>2011 - 2017</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Nicolás Satragno</mal:name>
      <mal:email>nsatragno@gmail.com</mal:email>
      <mal:years>2012 - 2013</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Jorge González</mal:name>
      <mal:email>jorgegonz@svn.gnome.org</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  </info>

  <title>ComboBoxText</title>
  <media type="image" mime="image/png" src="media/combobox.png"/>
  <p>Un «ComboBox» es un menú desplegable. La diferencia entre un <link xref="combobox.js">ComboBox</link> y un «ComboBoxText» es que este sólo tiene opciones básicas de texto, mientras que un «ComboBox» completo usa un «ListStore» o «TreeStore» (que son básicamente hojas de cálculo) para mostrar cosas como opciones de bifurcación, o imágenes junto a cada opción.</p>
  <note><p>A menos que necesite las características adicionales de un «ComboBox» completo, o si se siente cómodo trabajando con «ListStore» y «TreeStore», encontrará mucho más simple usar un «ComboBoxText» siempre que sea posible.</p></note>
    <links type="section"/>

  <section id="imports">
    <title>Bibliotecas que importar</title>
    <code mime="application/javascript">
#!/usr/bin/gjs

const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
</code>
    <p>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.</p>
  </section>

  <section id="applicationwindow">
    <title>Crear la ventana de la aplicación</title>
    <code mime="application/javascript">
const ComboBoxTextExample = new Lang.Class ({
    Name: 'ComboBoxText Example',

    // Create the application itself
    _init: function () {
        this.application = new Gtk.Application ({
            application_id: 'org.example.jscomboboxtext'});

        // 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 builds the UI
    _onStartup: function () {
        this._buildUI ();
    },
</code>
    <p>Todo el código de este ejemplo va en la clase «MessageDialogExample». El código anterior crea una <link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link> para que vayan los widgets y la ventana.</p>
    <code mime="application/javascript">
    // 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: "Welcome to GNOME",
            default_width: 200,
            border_width: 10 });
</code>
    <p>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 <link xref="GtkApplicationWindow.js">Gtk.ApplicationWindow</link> nueva para poner dentro todos los widgets.</p>
  </section>

  <section id="comboboxtext">
    <title>Crear el ComboBoxText</title>
    <code mime="application/javascript">
        // Create the combobox
        this._comboBoxText = new Gtk.ComboBoxText();

        // Populate the combobox
        let distros = ["Select distribution", "Fedora", "Mint", "Suse"];
        for (let i = 0; i &lt; distros.length; i++)
            this._comboBoxText.append_text (distros[i]);
        this._comboBoxText.set_active (0);

        // Connect the combobox's 'changed' signal to our callback function
        this._comboBoxText.connect ('changed', Lang.bind (this, this._onComboChanged));
</code>
    <p>Después de crear el «ComboBoxText», se usa su método <file>append_text</file> para añadirle cadenas de texto. Al igual que las entradas en una matriz, cada una tiene un número para identificarlas, comenzando por el 0. Para hacer las cosas más simples, puede crear una matriz para los datos del «ComboBoxText», y después usar un bucle «for» para añadirlos en orden, como aquí.</p>
    <p>Después de poblar el «ComboBoxText», se activa su primera entrada, para ver la línea «Seleccionar distribución» antes de pulsarlo. Después se conecta su señal <file>changed</file> a la función «_onComboChanged», para que se llame siempre que haga una selección nueva del menú desplegable.</p>
    <note><p>Si quiere añadirle una entrada a un «ComboBoxText», puede usar el método <file>insert_text</file>. Y si prefiere usar una cadena de texto como identificación de cada entrada en lugar de solo números, puede usar los métodos <file>append</file> e <file>insert</file>. Consulte los enlaces al final de este tutorial para ver detalles sobre su uso.</p></note>

    <code mime="application/javascript">
        // Add the combobox to the window
        this._window.add (this._comboBoxText);

        // Show the window and all child widgets
        this._window.show_all();
    },
</code>
    <p>Finalmente, se añade el «ComboBoxText» a la ventana, y se le dice que se muestre con su widget.</p>
  </section>

  <section id="function">
    <title>Función que maneja su selección</title>
    <code mime="application/javascript">
    _onComboChanged: function () {

        // The responses we'll use for our messagedialog
        let responses = ["",
            "Fedora is a community distro sponsored by Red Hat.",
            "Mint is a popular distro based on Ubuntu.",
            "SUSE is a name shared by two separate distros."];
</code>
    <p>Se va a crear un <link xref="messagedialog.js">MessageDialog</link> emergente, que muestre un mensaje a partir de qué distribución elija. Primero, se crea la matriz de respuestas para usar. Dado que la primera cadena del «ComboBoxText» es solo el mensaje «Seleccione distribución», la primera cadena de la matriz está vacía.</p>

    <code mime="application/javascript">
        // Which combobox item is active?
        let activeItem = this._comboBoxText.get_active();

        // No messagedialog if you chose "Select distribution"
        if (activeItem != 0) {
            this._popUp = new Gtk.MessageDialog ({
                transient_for: this._window,
                modal: true,
                buttons: Gtk.ButtonsType.OK,
                message_type: Gtk.MessageType.INFO,
                text: responses[activeItem]});

            // Connect the OK button to a handler function
            this._popUp.connect ('response', Lang.bind (this, this._onDialogResponse));

            // Show the messagedialog
            this._popUp.show();
        }

    },
</code>
    <p>Antes de mostrar un «MessageDialog», se verifica que no ha elegido el mensaje «Seleccionar distribución». Después de eso, se establece su texto a la entrada en la matriz que le corresponde a la entrada activa en el «ComboBoxText». Esto se hace usando el método <file>get_active</file>, que devuelve la identificación numérica de su selección.</p>
    <note><p>Otros métodos que puede usar incluyen <file>get_active_id</file>, que devuelve la identificación de texto que asignó <file>append</file>, y <file>get_active_text</file>, que devuelve el texto completo de la cadena que seleccionó.</p></note>
    <p>Después de crear el «MessageDialog», se conecta su señal «response» a la función «onDialogResponse», y se le dice que se muestre.</p>

    <code mime="application/javascript">
    _onDialogResponse: function () {

        this._popUp.destroy ();

    }

});
</code>
    <p>Dado que el único botón que tiene el «MessageDialog» es un botón aceptar, no se necesita verificar su «response_id» para ver qué botón se pulsó. Todo lo que se hace aquí es destruir la ventana emergente.</p>

    <code mime="application/javascript">
// Run the application
let app = new ComboBoxTextExample ();
app.application.run (ARGV);
</code>
    <p>Finalmente, se crea una instancia nueva de la clase ComboBoxTextExample terminada, y se ejecuta la aplicación.</p>
  </section>

  <section id="complete">
    <title>Código de ejemplo completo</title>
<code mime="application/javascript" style="numbered">#!/usr/bin/gjs

imports.gi.versions.Gtk = '3.0';
const Gtk = imports.gi.Gtk;

class ComboBoxTextExample {

    // Create the application itself
    constructor() {
        this.application = new Gtk.Application ({
            application_id: 'org.example.jscomboboxtext'});

        // 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 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,
            title: "Welcome to GNOME",
            default_width: 200,
            border_width: 10 });

        // Create the combobox
        this._comboBoxText = new Gtk.ComboBoxText();

        // Populate the combobox
        let distros = ["Select distribution", "Fedora", "Mint", "Suse"];
        for (let i = 0; i &lt; distros.length; i++)
            this._comboBoxText.append_text (distros[i]);
        this._comboBoxText.set_active (0);

        // Connect the combobox's 'changed' signal to our callback function
        this._comboBoxText.connect ('changed', this._onComboChanged.bind(this));

        // Add the combobox to the window
        this._window.add (this._comboBoxText);

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

    _onComboChanged() {

        // The responses we'll use for our messagedialog
        let responses = ["",
            "Fedora is a community distro sponsored by Red Hat.",
            "Mint is a popular distro based on Ubuntu.",
            "SUSE is a name shared by two separate distros."];

        // Which combobox item is active?
        let activeItem = this._comboBoxText.get_active();

        // No messagedialog if you chose "Select distribution"
        if (activeItem != 0) {
            this._popUp = new Gtk.MessageDialog ({
                transient_for: this._window,
                modal: true,
                buttons: Gtk.ButtonsType.OK,
                message_type: Gtk.MessageType.INFO,
                text: responses[activeItem]});

            // Connect the OK button to a handler function
            this._popUp.connect ('response', this._onDialogResponse.bind(this));

            // Show the messagedialog
            this._popUp.show();
        }

    }

    _onDialogResponse() {

        this._popUp.destroy ();

    }

};

// Run the application
let app = new ComboBoxTextExample ();
app.application.run (ARGV);
</code>
  </section>

  <section id="in-depth">
    <title>Documentación en profundidad</title>
<p>En este ejemplo se usa lo siguiente:</p>
<list>
  <item><p><link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link></p></item>
  <item><p><link href="http://developer.gnome.org/gtk3/stable/GtkApplicationWindow.html">Gtk.ApplicationWindow</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.ComboBoxText.html">Gtk.ComboBoxText</link></p></item>
  <item><p><link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.MessageDialog.html">Gtk.MessageDialog</link></p></item>
</list>
  </section>
</page>