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="scale.js" xml:lang="es">
  <info>
  <title type="text">Escala (JavaScript)</title>
    <link type="guide" xref="beginner.js#entry"/>
    <revision version="0.1" date="2012-06-20" status="draft"/>

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

    <desc>Un deslizador que corresponde a un valor numérico</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>Escala</title>
  <media type="image" mime="image/png" src="media/scalepenguins.png"/>
  <p>Una escala es un deslizador horizontal o vertical, que representa un valor dentro de un rango numérico. Cuando crea una escala nueva, establece cuál es su posición predeterminada, cuáles son los números en la parte inferior y superior del rango, y cosas como cuánto sube o baja cuando pulsa en la escala o en cada lado de la perilla. Para no tener que introducir todo eso cada vez que cree una escala nueva, puede crear un objeto llamado ajuste que registra todo eso, y decirle a cada escala nueva que use ese ajuste.</p>
  <p>Esta escala es un widget simple que le permite ajustar el tamaño de un iceberg en el que viven pingüinos. El número de pingüinos en el iceberg es el producto de los valores de ambos deslizadores. Juegue con ellos y vea qué sucede.</p>
    <links type="section"/>

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

const Gio = imports.gi.Gio;
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 ScaleExample = new Lang.Class({
    Name: 'Scale Example',

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

    // 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 ();
    },
</code>
    <p>Todo el código de este ejemplo va en la clase «ScaleExample». 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,
            border_width: 20,
            title: "Birds on a Floe"});
</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="button">
    <title>Crear las escalas</title>
    <code mime="application/javascript">
        // Create the horizontal scale
        this._hScale = Gtk.Scale.new_with_range (Gtk.Orientation.HORIZONTAL, 0.0, 100.0, 5.0);
        this._hScale.set_valign (Gtk.Align.START);
        this._hScale.set_value (50);
        this._hScale.set_digits (0);
        // this._hScale.set_draw_value (false);
</code>

    <p>El método nuevo «new_with_range» es una manera de crear un widget de escala. Los parámetros que toma son una <link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Orientation.html">Gtk.Orientation</link>, el valor mínimo, el valor máximo, y el incremento para un solo paso. Después de eso se usan los métodos de la escala para establecer su valor de inicio, y cuántos lugares decimales abarca. También se establece su alineación vertical en este caso, para controlar dónde aparece en la ventana.</p>
    <p>Se puede usar el método «set_draw_value» para decirle si muestra o no el número junto a la escala deslizante. En este ejemplo está comentado.</p>

    <code mime="application/javascript">
        // Create a master adjustment to use for the vertical (or any other) scale
        this._adjustment = new Gtk.Adjustment ({
            value: 95,
            lower: 0,
            upper: 100,
            step_increment: 5,
            page_increment: 10 });
</code>

    <p>Un ajuste es un objeto que se puede usar para simplificar las cosas cuando se crea una escala nueva. La propiedad «value» del ajuste es el valor predeterminado de la escala, mientras que «upper» y «lower» son los límites superior e inferior del rango numérico. Además, las valores de incremento muestran cuánto se mueve el deslizador cuando hace cosas como pulsarlo.</p>

    <code mime="application/javascript">
        // Create a vertical scale using the adjustment we just made
        this._vScale = new Gtk.Scale ({
            orientation: Gtk.Orientation.VERTICAL,
            adjustment: this._adjustment,
            digits: 0,
            // draw_value: false,
            margin_left: 10 });
</code>

    <p>Aquí se crea un objeto de escala nuevo usando «_adjustment» como su propiedad «ajuste». Este es un buen atajo. Sin embargo, todavía hay que decirle que redondee el lugar decimal. Tenga en cuenta que la propiedad «draw_value» está comentada; así es como se le dice que no muestre el número junto a la escala cuando está creando una de esta manera.</p>

    <code mime="application/javascript">
        // Create the label that shows the product of the two values
        this._product = (this._hScale.get_value() * this._vScale.get_value());
        this._label = new Gtk.Label ({
            label: (String(this._product) + " penguins on the iceberg."),
            height_request: 200,
            width_request: 200,
            wrap: true});

        // Connect the two scales to functions which recalculate the label
        this._hScale.connect ("value-changed", Lang.bind (this, this._recalc));
        this._vScale.connect ("value-changed", Lang.bind (this, this._recalc));
</code>

    <p>Se puede usar el método «get_value» para obtener el valor numérico en el que se estableció una escala. Después se puede hacer lo que se quiera con él, incluyendo multiplicar los dos valores de las escalas y hacer que una <link xref="label.js">etiqueta</link> muestre el producto. Se configura el texto de la etiqueta para que ajuste su línea, porque también se hace que muestre un mensaje tonto.</p>
    <p>Después de crear la etiqueta, se conectan las señales «value-changed» de las dos escalas a «_recalc», una función que recalculará el número de pingüinos en el iceberg y elaborará un mensaje nuevo.</p>

    <code mime="application/javascript">
        // Create a grid to arrange things in
        this._UIGrid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            margin_top: 20,
            margin_left: 20});

        // Attach everything to the grid
        this._UIGrid.attach (this._label, 0, 0, 1, 1);
        this._UIGrid.attach (this._hScale, 0, 1, 1, 1);
        this._UIGrid.attach (this._vScale, 1, 0, 1, 1);
</code>
    <p>Aquí se crea una <link xref="grid.js">rejilla</link> para poner todo dentro, después se le adjuntan todos los widgets. Tenga en cuenta que aquí y en algunos de los widgets se usan márgenes para mantener las cosas prolijamente espaciadas.</p>
    <code mime="application/javascript">
        // Add the grid to the window
        this._window.add (this._UIGrid);

        // Show the window and all child widgets
        this._window.show_all();
    },
</code>
    <p>Finalmente, se le añade la rejilla a la ventana, y después se le dice a la ventana que se muestre con todos sus widgets dentro.</p>
    </section>

    <section id="scales-handler">
    <title>Función que maneja el cambio de los valores de las escalas</title>

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

        // Figure out what the product of the two scales' values is
        var product = (this._hScale.get_value() * this._vScale.get_value());

        // Create a blank comment line in case there isn't a silly comment to make
        var comment = "";

        // Make a silly comment based on the number of penguins
        if (product &gt; 9000) {
            comment = "It's over 9000!";
        }
        else if (product &lt; 1000 &amp;&amp; product &gt; 0) {
            comment = "They're getting lonely.";
        }
        else if (product == 0) {
            comment = "They're all gone ...";
        }
        else comment = "";

        // Set ._label's new text
        this._label.set_label (String (product) + " penguins on the iceberg. " + comment);

    }

});
</code>
    <p>Recuerde, se puede obtener el valor de una escala usando su método «get_value». Aquí simplemente se recalcula cuál es el producto de los dos valores después de que se mueva una de las escalas, se añade un mensaje tonto dependiendo de cuántos pingüinos quedan, y se cambian las palabras en «_label» para mostrar el número y mensaje nuevos.</p>

    <code mime="application/javascript">
// Run the application
let app = new ScaleExample ();
app.application.run (ARGV);
</code>
    <p>Finalmente, se crea una instancia nueva de la clase «ScaleExample» 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 Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;

class ScaleExample {

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

        // 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: "Birds on a Floe"});

        // Create the horizontal scale
        this._hScale = Gtk.Scale.new_with_range (Gtk.Orientation.HORIZONTAL, 0.0, 100.0, 5.0);
        this._hScale.set_valign (Gtk.Align.START);
        this._hScale.set_value (50);
        this._hScale.set_digits (0);
        // this._hScale.set_draw_value (false);

        // Create a master adjustment to use for the vertical (or any other) scale
        this._adjustment = new Gtk.Adjustment ({
            value: 95,
            lower: 0,
            upper: 100,
            step_increment: 5,
            page_increment: 10 });

        // Create a vertical scale using the adjustment we just made
        this._vScale = new Gtk.Scale ({
            orientation: Gtk.Orientation.VERTICAL,
            adjustment: this._adjustment,
            digits: 0,
            // draw_value: false,
            margin_left: 10 });

        // Create the label that shows the product of the two values
        this._product = (this._hScale.get_value() * this._vScale.get_value());
        this._label = new Gtk.Label ({
            label: (String(this._product) + " penguins on the iceberg."),
            height_request: 200,
            width_request: 200,
            wrap: true});

        // Connect the two scales to functions which recalculate the label
        this._hScale.connect ("value-changed", this._recalc.bind(this));
        this._vScale.connect ("value-changed", this._recalc.bind(this));

        // Create a grid to arrange things in
        this._UIGrid = new Gtk.Grid ({
            halign: Gtk.Align.CENTER,
            valign: Gtk.Align.CENTER,
            margin_top: 20,
            margin_left: 20});

        // Attach everything to the grid
        this._UIGrid.attach (this._label, 0, 0, 1, 1);
        this._UIGrid.attach (this._hScale, 0, 1, 1, 1);
        this._UIGrid.attach (this._vScale, 1, 0, 1, 1);

        // Add the grid to the window
        this._window.add (this._UIGrid);

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

    _recalc() {

        // Figure out what the product of the two scales' values is
        var product = (this._hScale.get_value() * this._vScale.get_value());

        // Create a blank comment line in case there isn't a silly comment to make
        var comment = "";

        // Make a silly comment based on the number of penguins
        if (product &gt; 9000) {
            comment = "It's over 9000!";
        }
        else if (product &lt; 1000 &amp;&amp; product &gt; 0) {
            comment = "They're getting lonely.";
        }
        else if (product == 0) {
            comment = "They're all gone ...";
        }
        else comment = "";

        // Set ._label's new text
        this._label.set_label (String (product) + " penguins on the iceberg. " + comment);
    }
};

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

  <section id="in-depth">
    <title>Documentación en profundidad</title>
<list>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Adjustment.html">Gtk.Adjustment</link></p></item>
  <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.Grid.html">Gtk.Grid</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Label.html">Gtk.Label</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.Scale.html">Gtk.Scale</link></p></item>
</list>
  </section>
</page>