<?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="combobox.js" xml:lang="de">
  <info>
  <title type="text">ComboBox (JavaScript)</title>
    <link type="guide" xref="beginner.js#menu-combo-toolbar"/>
    <link type="seealso" xref="GtkApplicationWindow.js"/>
    <link type="seealso" xref="comboboxtext.js"/>
    <link type="seealso" xref="messagedialog.js"/>
    <link type="seealso" xref="treeview_simple_liststore.js"/>
    <revision version="0.1" date="2012-07-09" status="draft"/>

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

    <desc>A customizable drop-down menu</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Mario Blättermann</mal:name>
      <mal:email>mario.blaettermann@gmail.com</mal:email>
      <mal:years>2011, 2013, 2016, 2018</mal:years>
    </mal:credit>
  </info>

  <title>ComboBox</title>
  <media type="image" mime="image/png" src="media/combobox_multicolumn.png"/>
  <p>A ComboBox is an extremely customizable drop-down menu. It holds the equivalent of a <link xref="treeview_simple_liststore.js">TreeView</link> widget that appears when you click on it, complete with a ListStore (basically a spreadsheet) that says what's in the rows and columns. In this example, our ListStore has the name of each option in one column, and the name of a stock icon in the other, which the ComboBox then turns into an icon for each option.</p>
  <p>You select a whole horizontal row at a time, so the icons aren't treated as separate options. They and the text beside them make up each option you can click on.</p>
  <note style="tip"><p>Working with a ListStore can be time-consuming. If you just want a simple text-only drop-down menu, take a look at the <link xref="comboboxtext.js">ComboBoxText</link>. It doesn't take as much time to set up, and is easier to work with.</p></note>
    <links type="section"/>

  <section id="imports">
    <title>Zu importierende Bibliotheken</title>
    <code mime="application/javascript">
#!/usr/bin/gjs

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

const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
</code>
    <p>These are the libraries we need to import for this application to run. Remember that the line which tells GNOME that we're using Gjs always needs to go at the start.</p>
  </section>

  <section id="applicationwindow">
    <title>Entwurf des Anwendungsfensters</title>
    <code mime="application/javascript">
class ComboBoxExample {

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

        // 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 ();
    }
</code>
    <p>All the code for this sample goes in the ComboBoxExample class. The above code creates a <link href="http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gtk.Application.html">Gtk.Application</link> for our widgets and window to go in.</p>
    <code mime="application/javascript">
    // 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 });
</code>
    <p>The _buildUI function is where we put all the code to create the application's user interface. The first step is creating a new <link xref="GtkApplicationWindow.js">Gtk.ApplicationWindow</link> to put all our widgets into.</p>
  </section>

  <section id="liststore">
    <title>Creating the ListStore</title>
    <code mime="application/javascript">
        // Create the liststore to put our options in
        this._listStore = new Gtk.ListStore();
        this._listStore.set_column_types ([
            GObject.TYPE_STRING,
            GObject.TYPE_STRING]);
</code>
    <p>This ListStore works like the one used in the <link xref="treeview_simple_liststore.js">TreeView</link> example. We're giving it two columns, both strings, because one of them will contain the names of <link href="https://developer.gnome.org/gtk3/3.4/gtk3-Stock-Items.html">stock Gtk icons</link>.</p>
    <p>If we'd wanted to use our own icons that weren't already built in to GNOME, we'd have needed to use the <file>gtk.gdk.Pixbuf</file> type instead. Here are a few other types you can use:</p>
    <list>
      <item><p><file>GObject.TYPE_BOOLEAN</file> -- True or false</p></item>
      <item><p><file>GObject.TYPE_FLOAT</file> -- A floating point number (one with a decimal point)</p></item>
      <item><p><file>GObject.TYPE_STRING</file> -- A string of letters and numbers</p></item>
    </list>
    <note style="tip"><p>You need to put the line <file>const GObject = imports.gi.GObject;</file> at the start of your application's code, like we did in this example, if you want to be able to use GObject types.</p></note>

    <code mime="application/javascript">
        // This array holds our list of options and their icons
        let options = [{ name: "Select" },
            { name: "New", icon: Gtk.STOCK_NEW },
            { name: "Open", icon: Gtk.STOCK_OPEN },
            { name: "Save", icon: Gtk.STOCK_SAVE }];

        // Put the options in the liststore
        for (let i = 0; i &lt; options.length; i++ ) {
            let option = options[i];
            let iter = this._listStore.append();
            this._listStore.set (iter, [0], [option.name]);
            if ('icon' in option)
                this._listStore.set (iter, [1], [option.icon]);
        }
</code>
    <p>Here we create an array of the text options and their corresponding icons, then put them into the ListStore in much the same way we would for a <link xref="treeview_simple_liststore.js">TreeView's</link> ListStore. We only want to put an icon in if there's actually an icon in the options array, so we make sure to check for that first.</p>
    <note style="tip"><p>"Select" isn't really an option so much as an invitation to click on our ComboBox, so it doesn't need an icon.</p></note>
  </section>

  <section id="combobox">
    <title>Creating the ComboBox</title>
    <code mime="application/javascript">
        // Create the combobox
        this._comboBox = new Gtk.ComboBox({
            model: this._listStore});
</code>
    <p>Each ComboBox has an underlying "model" it takes all its options from. You can use a TreeStore if you want to have a ComboBox with branching options. In this case, we're just using the ListStore we already created.</p>
    <code mime="application/javascript">
        // Create some cellrenderers for the items in each column
        let rendererPixbuf = new Gtk.CellRendererPixbuf();
        let rendererText = new Gtk.CellRendererText();

        // Pack the renderers into the combobox in the order we want to see
        this._comboBox.pack_start (rendererPixbuf, false);
        this._comboBox.pack_start (rendererText, false);

        // Set the renderers to use the information from our liststore
        this._comboBox.add_attribute (rendererText, "text", 0);
        this._comboBox.add_attribute (rendererPixbuf, "stock_id", 1);
</code>
    <p>This part, again, works much like creating CellRenderers and packing them into the columns of a <link xref="treeview_simple_liststore.js">TreeView</link>. The biggest difference is that we don't need to create the ComboBox's columns as separate objects. We just pack the CellRenderers into it in the order we want them to show up, then tell them to pull information from the ListStore (and what type of information we want them to expect).</p>
    <p>We use a CellRendererText to show the text, and a CellRendererPixbuf to show the icons. We can store the names of the icons' stock types as strings, but when we display them we need a CellRenderer that's designed for pictures.</p>
    <note style="tip"><p>Just like with a TreeView, the "model" (in this case a ListStore) and the "view" (in this case our ComboBox) are separate. Because of that, we can do things like have the columns in one order in the ListStore, and then pack the CellRenderers that correspond to those columns into the ComboBox in a different order. We can even create a TreeView or other widget that shows the information in the ListStore in a different way, without it affecting our ComboBox.</p></note>

    <code mime="application/javascript">
        // Set the first row in the combobox to be active on startup
        this._comboBox.set_active (0);

        // Connect the combobox's 'changed' signal to our callback function
        this._comboBox.connect ('changed', this._onComboChanged.bind(this));
</code>
    <p>We want the "Select" text to be the part people see at first, that gets them to click on the ComboBox. So we set it to be the active entry. We also connect the ComboBox's <file>changed</file> signal to a callback function, so that any time someone clicks on a new option something happens. In this case, we're just going to show a popup with a little haiku.</p>

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

        // Show the window and all child widgets
        this._window.show_all();
    }
</code>
    <p>Finally, we add the ComboBox to the window, and tell the window to show itself and everything inside it.</p>
  </section>

  <section id="function">
    <title>Function which handles your selection</title>
    <code mime="application/javascript">
    _selected() {

        // The silly pseudohaiku that we'll use for our messagedialog
        let haiku = ["",
            "You ask for the new\nwith no thought for the aged\nlike fallen leaves trod.",
            "Like a simple clam\nrevealing a lustrous pearl\nit opens for you.",
            "A moment in time\na memory on the breeze\nthese things can't be saved."];
</code>
    <p>We're going to create a pop-up <link xref="messagedialog.js">MessageDialog</link>, which shows you a silly haiku based on which distro you select. First, we create the array of haiku to use. Since the first string in our ComboBox is just the "Select" message, we make the first string in our array blank.</p>

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

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

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

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

    }
</code>
    <p>Before showing a MessageDialog, we first test to make sure you didn't choose the "Select" message. After that, we set its text to be the haiku in the array that corresponds to the active entry in our ComboBoxText. We do that using the <file>get_active</file> method, which returns the number ID of your selection.</p>
    <note style="tip"><p>Other methods you can use include <file>get_active_id</file>, which returns the text ID assigned by <file>append</file>, and <file>get_active_text</file>, which returns the full text of the string you selected.</p></note>
    <p>After we create the MessageDialog, we connect its response signal to the _onDialogResponse function, then tell it to show itself.</p>

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

        this._popUp.destroy ();

    }

};
</code>
    <p>Since the only button the MessageDialog has is an OK button, we don't need to test its response_id to see which button was clicked. All we do here is destroy the popup.</p>

    <code mime="application/javascript">
// Run the application
let app = new ComboBoxExample ();
app.application.run (ARGV);
</code>
    <p>Finally, we create a new instance of the finished ComboBoxExample class, and set the application running.</p>
  </section>

  <section id="complete">
    <title>Complete code sample</title>
<code mime="application/javascript" style="numbered">#!/usr/bin/gjs

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

const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;

class ComboBoxExample {

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

        // 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 liststore to put our options in
        this._listStore = new Gtk.ListStore();
        this._listStore.set_column_types ([
            GObject.TYPE_STRING,
            GObject.TYPE_STRING]);

        // This array holds our list of options and their icons
        let options = [{ name: "Select" },
            { name: "New", icon: Gtk.STOCK_NEW },
            { name: "Open", icon: Gtk.STOCK_OPEN },
            { name: "Save", icon: Gtk.STOCK_SAVE }];

        // Put the options in the liststore
        for (let i = 0; i &lt; options.length; i++ ) {
            let option = options[i];
            let iter = this._listStore.append();
            this._listStore.set (iter, [0], [option.name]);
            if ('icon' in option)
                this._listStore.set (iter, [1], [option.icon]);
        }

        // Create the combobox
        this._comboBox = new Gtk.ComboBox({
            model: this._listStore});

        // Create some cellrenderers for the items in each column
        let rendererPixbuf = new Gtk.CellRendererPixbuf();
        let rendererText = new Gtk.CellRendererText();

        // Pack the renderers into the combobox in the order we want to see
        this._comboBox.pack_start (rendererPixbuf, false);
        this._comboBox.pack_start (rendererText, false);

        // Set the renderers to use the information from our liststore
        this._comboBox.add_attribute (rendererText, "text", 0);
        this._comboBox.add_attribute (rendererPixbuf, "stock_id", 1);

        // Set the first row in the combobox to be active on startup
        this._comboBox.set_active (0);

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

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

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

    _onComboChanged() {

        // The silly pseudohaiku that we'll use for our messagedialog
        let haiku = ["",
            "You ask for the new\nwith no thought for the aged\nlike fallen leaves trod.",
            "Like a simple clam\nrevealing a lustrous pearl\nit opens for you.",
            "A moment in time\na memory on the breeze\nthese things can't be saved."];

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

        // No messagedialog if you choose "Select"
        if (activeItem != 0) {
            this._popUp = new Gtk.MessageDialog ({
                transient_for: this._window,
                modal: true,
                buttons: Gtk.ButtonsType.OK,
                message_type: Gtk.MessageType.INFO,
                text: haiku[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 ComboBoxExample ();
app.application.run (ARGV);
</code>
  </section>

  <section id="in-depth">
    <title>Weiterführende Dokumentation</title>
<p>
  In this sample we used the following:
</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.CellRendererPixbuf.html">Gtk.CellRendererPixbuf</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.CellRendererText.html">Gtk.CellRendererText</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.ComboBox.html">Gtk.ComboBox</link></p></item>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.ListStore.html">Gtk.ListStore</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>
  <item><p><link href="http://www.roojs.org/seed/gir-1.2-gtk-3.0/gjs/Gtk.TreeIter.html">Gtk.TreeIter</link></p></item>
</list>
  </section>
</page>
