# RadioButton (Javascript)

Taryn Fox
jewelfox@fursona.net 2012
Endast en åt gången kan väljas
Sebastian Rasmussen
sebras@gmail.com 2019
Anders Jonsson
anders.jonsson@norsjovallen.se 2021

# RadioButton

RadioButtons are named after old-style car radios, which had buttons for switching between channel presets. Because the radio could only be tuned to one station at a time, only one button could be pressed in at a time; if you pressed a new one, the one that was already pressed in would pop back out. That's how these buttons work, too.

Each RadioButton needs a text label and a group. Only one button in a group can be selected at a time. You don't name each group; you just set new RadioButtons to be part of the same group as an existing one. If you create a new one outside of a group, it automatically creates a new group for it to be part of.

# Bibliotek att importera

#!/usr/bin/gjs

const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Lang = imports.lang;

Detta är biblioteken som vi behöver importera för att detta program ska köras. Kom ihåg att raden som säger till GNOME att vi använder Gjs alltid behöver vara först.

# Skapa programfönstret

const RadioButtonExample = new Lang.Class({ Name: 'RadioButton-exempel',

// Skapa programmet i sig _init: function() { this.application = new Gtk.Application({ application_id: 'org.example.jsradiobutton', flags: Gio.ApplicationFlags.FLAGS_NONE });

// Anslut ”activate”- och ”startup”-signaler till återanropsfunktionerna this.application.connect('activate', Lang.bind(this, this._onActivate)); this.application.connect('startup', Lang.bind(this, this._onStartup)); },

// Återanropsfunktion för ”activate”-signal, visar fönstret när den aktiveras _onActivate: function() { this._window.present(); },

// Återanropsfunktion för ”startup”-signal bygger användargränssnittet _onStartup: function() { this._buildUI (); },

All kod för detta exempel hamnar i klassen RadioButtonExample. Koden ovan skapar en Gtk.Application att ha våra komponenter och fönstret i.

// Bygg programmets användargränssnitt _buildUI: function() {

// Skapa programfönstret this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, border_width: 20, title: "Reseplanering"});

_buildUI-funktionen är var vi stoppar all kod för att skapa programmets användargränssnitt. Det första steget är att skapa ett nytt Gtk.ApplicationWindow att stoppa alla våra komponenter i.

# Skapa radioknapparna

// Skapa en etikett för den första gruppen knappar this._placeLabel = new Gtk.Label ({label: "Vart vill du resa?"});

We use a Gtk.Label to set each group of RadioButtons apart. Nothing will stop you from putting RadioButtons from all different groups wherever you want, so if you want people to know which ones go together you need to organize things accordingly.

// Skapa tre radioknappar på tre olika sätt this._place1 = new Gtk.RadioButton ({label: "Stranden"});

this._place2 = Gtk.RadioButton.new_from_widget (this._place1); this._place2.set_label ("Månen");

this._place3 = Gtk.RadioButton.new_with_label_from_widget (this._place1, "Antarktis"); // this._place3.set_active (true);

Here are three different ways to create RadioButtons. The first is the usual way, where we create a new Gtk.RadioButton and assign its properties at the same time. The second and third use functions which automatically handle some of the properties; new_from_widget takes a single argument, the RadioButton that you want to put this new one in the same group as. Meanwhile, new_with_label_from_widget takes that and the RadioButton's label at the same time.

The first RadioButton in a group is the one that's selected by default. Try uncommenting the last line in this sample code to see how you can set a different one to be the default selection.

// Skapa en etikett för den andra gruppen knappar this._thingLabel = new Gtk.Label ({label: "Och vad skulle du vilja ta med dig?" });

// Skapa tre till radioknappar this._thing1 = new Gtk.RadioButton ({label: "Pingviner" }); this._thing2 = new Gtk.RadioButton ({label: "Sololja", group: this._thing1 }); this._thing3 = new Gtk.RadioButton ({label: "En rymddräkt", group: this._thing1 });

Här skapar vi etiketten för den andra gruppen knappar, och skapar sedan dem alla på samma sätt.

# Skapa resten av användargränssnittet

// Skapa en OK-standardknapp this._okButton = new Gtk.Button ({ label: 'gtk-ok', use_stock: 'true', halign: Gtk.Align.END });

// Anslut knappen till funktionen som hanterar att klicka på den this._okButton.connect ('clicked', Lang.bind (this, this._okClicked));

Denna kod skapar en Gtk.Button och binder den till en funktion som kommer visa ett fånigt meddelande för folk när de klickar OK, beroende på vilken RadioButton som valts.

To make sure the button's "OK" label shows up properly in every language that GNOME is translated into, remember to use one of Gtk's stock button types.

// 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);

We use a separate Gtk.Grid to organize each group of radio buttons. This way we can change the layout with less fuss later on. The second Grid has a margin on top, to visually separate the two sets of choices.

After we've organized them, we put them into a third, master Grid, along with the OK button. Then we attach that to the window.

// Visa fönstret och alla barnkomponenter this._window.show_all(); },

Finally, we tell the window and everything inside it to become visible when the application is run.

# Funktion som hanterar ditt val

_okClicked: function () {

// Skapa en poppupp som visar ett fånigt meddelande this._travel = new Gtk.MessageDialog ({ transient_for: this._window, modal: true, message_type: Gtk.MessageType.OTHER, buttons: Gtk.ButtonsType.OK, text: this._messageText() });

// Visa poppuppen this._travel.show();

// Bind OK-knappen till funktionen som stänger poppuppen this._travel.connect ("response", Lang.bind (this, this._clearTravelPopUp));

},

When you click OK, a Gtk.MessageDialog appears. This function creates and displays the popup window, then binds its OK button to a function that closes it. What text appears in the popup depends on the _messageText() function, which returns a different value depending on which set of options you chose.

_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;

},

The get_active() method is how we can tell which RadioButton's pressed in. This function returns a different silly message depending on which set of buttons was pressed. Its return value is used as the MessageDialog's text property.

_clearTravelPopUp: function () {

this._travel.destroy();

}

});

This function is called when the MessageDialog's OK button is pressed. It simply makes the popup go away.

// Kör programmet let app = new RadioButtonExample (); app.application.run (ARGV);

Slutligen skapar vi en ny instans av den slutförda RadioButtonExample-klassen, och startar programmet.

# Fullständigt kodexempel

#!/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);

# Djupgående dokumentation

Gtk.Application

Gtk.ApplicationWindow

Gtk.Button

Gtk.Grid

Gtk.Label

Gtk.RadioButton