GUI component interaction: Difference between revisions

m
imported>Arakov
 
(35 intermediate revisions by 16 users not shown)
Line 13:
{{omit from|Lotus 123}}
{{omit from|Maxima}}
{{omit from|Minimal BASIC|It does not handle GUI}}
{{omit from|Nascom BASIC|It does not handle GUI}}
{{omit from|PARI/GP}}
{{omit from|PostScript}}
{{omit from|Retro}}
{{omit from|SQL PL|It does not handle GUI}}
{{omit from|Tiny BASIC|It does not handle GUI}}
 
{{omit from|Palo Alto Tiny BASIC|It does not handle GUI}}
 
Almost every application needs to communicate with the user in some way.
Line 51 ⟶ 54:
 
=={{header|1C}}==
<syntaxhighlight lang="text">
&НаСервере
Процедура ДобавитьЭлементы()
Line 110 ⟶ 113:
КонецПроцедуры
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 116 ⟶ 119:
 
interaction.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Gtk.Main;
Line 273 ⟶ 276:
 
Gtk.Main.Main;
end Interaction;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">GUI, add, Edit,Number w50 vUserInput gMakeSure, 0 ; Number Specifies Numbers-only, but other characters can still be pasted in,
; Making our own check necessary. (MakeSure)
 
Line 330 ⟶ 333:
ExitApp ; Makes sure the script exits when the window is closed,
; Otherwise the script is persistent because it contains
; a timer.</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
Requires BaCon version 4.0.1 or higher, using GTK3.
<syntaxhighlight lang="bacon">OPTION GUI TRUE
PRAGMA GUI gtk3
 
DECLARE (*show)() = gtk_widget_show_all TYPE void
DECLARE (*hide)() = gtk_widget_hide TYPE void
 
gui = GUIDEFINE(" \
{ type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=200 } \
{ type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
{ type=SPIN_BUTTON name=spin parent=box numeric=TRUE } \
{ type=BUTTON_BOX name=bbox parent=box } \
{ type=BUTTON name=increment parent=bbox callback=clicked label=\"Increment\" } \
{ type=BUTTON name=random parent=bbox callback=clicked label=\"Random\" } \
{ type=MESSAGE_DIALOG name=confirm callback=delete-event callback=response,yesno message-type=GTK_MESSAGE_WARNING buttons=GTK_BUTTONS_YES_NO title=\"Warning\" text=\"Get random number?\" }")
 
CALL GUISET(gui, "spin", "adjustment", gtk_adjustment_new(0, 0, MAXNUM(float), 1, 1, 0))
 
DECLARE answer TYPE int*
DECLARE input TYPE FLOATING
 
WHILE TRUE
event$ = GUIEVENT$(gui, TRUE)
SELECT TOKEN$(event$, 1)
CASE "window"
BREAK
CASE "increment"
CALL GUIGET(gui, "spin", "value", &input)
CALL GUISET(gui, "spin", "value", input+1)
CASE "random"
CALL GUIFN(gui, "confirm", show)
CASE "yesno"
answer = (intptr_t)DEC(TOKEN$(event$, 2))
IF *answer = GTK_RESPONSE_YES THEN CALL GUISET(gui, "spin", "value", RANDOM(MAXNUM(float)))
CALL GUIFN(gui, "confirm", hide)
ENDSELECT
WEND</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
Line 363 ⟶ 406:
SYS "MessageBox", !form%, "Set to a random value?", "Confirm", MB_YESNO TO reply%
IF reply% = IDYES THEN SYS "SetDlgItemInt", !form%, 101, RND(10000), 1
ENDPROC</langsyntaxhighlight>
{{Out}}
<p>[[File:Guiintbbc.gif]]</p>
Line 372 ⟶ 415:
<pre>file main.c</pre>
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
Line 419 ⟶ 462:
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {
return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );
}</langsyntaxhighlight>
 
<pre>file resource.h</pre>
 
<langsyntaxhighlight lang="c">#define IDD_DLG 101
#define IDC_INPUT 1001
#define IDC_INCREMENT 1002
#define IDC_RANDOM 1003
#define IDC_QUIT 1004</langsyntaxhighlight>
 
<pre>file resource.rc</pre>
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
Line 444 ⟶ 487:
PUSHBUTTON "Random", IDC_RANDOM, 62, 25, 50, 14
PUSHBUTTON "Quit", IDC_QUIT, 117, 25, 30, 14
}</langsyntaxhighlight>
 
=={{header|C++}}==
with library Qt 4.4 , using (under Linux) first qmake -project and then qmake -o Makefile <projectfile>, then make
<pre>file interaction.h</pre>
<langsyntaxhighlight lang="cpp">#ifndef INTERACTION_H
#define INTERACTION_H
#include <QWidget>
Line 470 ⟶ 513:
void findRandomNumber( ) ;
} ;
#endif</langsyntaxhighlight>
<pre>file interaction.cpp</pre>
<langsyntaxhighlight lang="cpp">#include <QPushButton>
#include <QLineEdit>
#include <QMessageBox>
Line 519 ⟶ 562:
break ;
}
}</langsyntaxhighlight>
<pre>file main.cpp </pre>
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include "interaction.h"
 
Line 529 ⟶ 572:
theWidget.show( ) ;
return app.exec( ) ;
}</langsyntaxhighlight>
 
===C++11===
Line 536 ⟶ 579:
<pre>main.cpp</pre>
 
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
Line 581 ⟶ 624:
 
return app.exec();
}</langsyntaxhighlight>
 
=={{header|C_sharp|C#}}==
C# 3.0 with Windows Forms; compile as csc -t:winexe Program.cs on MS.NET or as gmcs -t:winexe Program.cs on Mono.
<langsyntaxhighlight lang="csharp">using System;
using System.ComponentModel;
using System.Windows.Forms;
Line 658 ⟶ 701:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{libheader|LTK}}
<langsyntaxhighlight lang="lisp">
;; Using the LTK library...
 
Line 703 ⟶ 746:
(gui-test)
 
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
 
<syntaxhighlight lang Delphi="delphi">FILE: Unit1.pas</langsyntaxhighlight>
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Unit1;
 
Line 760 ⟶ 803:
end;
 
end.</langsyntaxhighlight>
<langsyntaxhighlight Delphilang="delphi">FILE: Unit1.dfm (No manual interaction!!! Will automatically be generated/modified when editing the GUI)</langsyntaxhighlight>
<syntaxhighlight lang="delphi">
<lang Delphi>
object Form1: TForm1
Left = 1899
Line 806 ⟶ 849:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Echolisp}}==
<langsyntaxhighlight lang="scheme">
(require 'interface)
 
Line 850 ⟶ 893:
 
(panel)
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import forms;
import extensions;
public class MainWindow : SDIDialog
{
Button btmIncrement;
Button btmRandom;
Edit txtNumber;
constructor new()
<= super new()
{
btmIncrement := Button.new();
btmRandom := Button.new();
txtNumber := Edit.new();
self
.appendControl:(btmIncrement)
.appendControl:(btmRandom)
.appendControl:(txtNumber);
 
self.Caption := "Rosseta Code";
self.setRegion(100, 100, 160180, 120140);
txtNumber.setRegion(720, 7, 140, 25);
txtNumber.Caption := "0";
btmIncrement.setRegion(720, 35, 140, 25);
btmIncrement.Caption := "Increment";
btmIncrement.onClick := (args){ self.onButtonIncrementClick() };
btmRandom.setRegion(720, 65, 140, 25);
btmRandom.Caption := "Random";
btmRandom.onClick := (args){ self.onButtonRandomClick() };
}
private onButtonIncrementClick()
{
var number := txtNumber.Value.toInt();
number := number + 1;
self.changeTextBoxValue(number)
}
private onButtonRandomClick()
{
if(messageDialog.showQuestion("Inf", "Really reset to random value?"))
{
self.changeTextBoxValue(randomGenerator.evalnextInt(99999999))
}
}
private changeTextBoxValue(number)
{
txtNumber.Caption := number.toString()
}
}</langsyntaxhighlight>
 
=={{header|Euphoria}}==
=== Alternative version using xforms script ===
<syntaxhighlight lang="euphoria">
include GtkEngine.e -- see OpenEuphoria.org
 
constant -- interface
form layout:
win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"),
<lang elena><Form X="100" Y="100" Width="160" Height="120" Caption="Rosseta Code">
pan = create(GtkBox,"orientation=vertical;spacing=10"),
<Edit ID="txtNumber" X="7" Y="7" Width="140" Height="25" Caption="0">
inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"),
</Edit>
box = create(GtkButtonBox),
<Button ID="btmIncrement" X="7" Y="35" Width="140" Height="25" Caption="Increment" onClick="onButtonIncrementClick">
btn1 = create(GtkButton,"gtk-add#_Increment","Increment"),
</Button>
btn2 = create(GtkButton,"gtk-help#_Random","Random")
<Button ID="btmRandom" X="7" Y="65" Width="140" Height="25" Caption="Random" onClick="onButtonRandomClick">
</Button>
add(win,pan)
</Form></lang>
add(pan,inp)
add(box,{btn1,btn2})
pack(pan,-box)
 
show_all(win)
main code:
main()
<lang elena>import xforms;
import forms;
import extensions;
-----------------------------
public class MainWindow
global function Validate() -- warns about invalid entry, does not prevent it;
{
-----------------------------
SDIForm form;
if not t_digit(trim_head(get("Input.text"),"- ")) then
return Warn(win,"Validate","This is not a valid number","Try again!")
Button btmIncrement;
end if
Button btmRandom;
return 1
Edit txtNumber;
end function
 
constructor new()
---------------------------
{
global function Increment()
form := xforms.executePath("main.xs", self);
---------------------------
set("Input.value",get("Input.value")+1)
btmIncrement := form.Controls.btmIncrement;
return 1
btmRandom := form.Controls.btmRandom;
end function
txtNumber := form.Controls.txtNumber;
 
}
------------------------
global function Random()
onButtonIncrementClick(sender)
------------------------
{
if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then
var number := txtNumber.Value.toInt();
set("Input.value",rand(1000))
end if
number := number + 1;
return 1
self.changeTextBoxValue(number)
end function
}
 
</syntaxhighlight>
onButtonRandomClick(sender)
 
{
=={{header|F_Sharp|F#}}==
if(messageDialog.showQuestion("Inf", "Really reset to random value?"))
<syntaxhighlight lang="fsharp">
{
// GUI component interaction. Nigel Galloway: June 13th., 2020
self.changeTextBoxValue(randomGenerator.eval(99999999))
let n=new System.Windows.Forms.Form(Size=new System.Drawing.Size(250,150))
}
let i=new System.Windows.Forms.TextBox(Location=new System.Drawing.Point(30,30),Text="0")
}
let g=new System.Windows.Forms.Label(Location=new System.Drawing.Point(135,33),Text="Value")
let e=new System.Windows.Forms.Button(Location=new System.Drawing.Point(30,70),Text="Increment")
private changeTextBoxValue(number)
let l=new System.Windows.Forms.Button(Location=new System.Drawing.Point(135,70),Text="Random")
{
n.Controls.AddRange([|i;g;e;l|])
txtNumber.Caption := number.toString()
let rand=new System.Random()
}
i.Leave.AddHandler(new System.EventHandler(fun _ _->i.Text<-try string(int(i.Text)) with |_->"0"))
e.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(int(i.Text)+1))))
dispatch() => form;
l.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(rand.Next()))))
}</lang>
System.Windows.Forms.Application.Run(n)
</syntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
using fwt
using gfx
Line 1,037 ⟶ 1,085:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#Include "windows.bi"
 
Line 1,082 ⟶ 1,130:
 
End
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum 1
_valLabel
_valFld
_incBtn
_rndBtn
end enum
 
_confirmAlert = 1
 
void local fn BuildWindow
window _window, @"GUI Components", (0,0,214,100), NSWindowStyleMaskTitled
textlabel _valLabel, @"Value:", (20,61,42,16)
textfield _valFld,, @"0", (68,59,126,21)
ControlSetFormat( _valFld, @"0123456789", YES, 3, 0 )
button _incBtn,,, @"Increment", (13,13,95,32)
button _rndBtn,,, @"Random", (106,13,95,32)
WindowMakeFirstResponder( _window, _valFld )
end fn
 
void local fn DoAppEvent( ev as long )
select ( ev )
case _appDidFinishLaunching
random
fn BuildWindow
end select
end fn
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _incBtn
long value = fn ControlIntegerValue( _valFld ) + 1
if ( value > 999 ) then value = 999
ControlSetStringValue( _valFld, fn StringWithFormat(@"%ld",value) )
case _rndBtn
long response = alert _confirmAlert,, @"Reset field", @"Do you want to reset the field to a random value?", @"OK;Cancel"
if ( response == NSAlertFirstButtonReturn )
ControlSetStringValue( _valFld, fn StringWithFormat(@"%ld",rnd(999)) )
end if
end select
end select
end fn
 
on appevent fn DoAppEvent
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
 
{{out}}
[[File:FB_GUIComponentInteraction.png]]
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">hValueBox As ValueBox 'We need a ValueBox
 
Public Sub Form_Open()
Line 1,140 ⟶ 1,247:
End If
 
End</langsyntaxhighlight>
 
=={{header|Go}}==
{{libheader|gotk3}}
{{trans|Vala}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,243 ⟶ 1,350:
window.ShowAll()
gtk.Main()
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight Haskelllang="haskell">import Graphics.UI.WX
import System.Random
 
Line 1,272 ⟶ 1,379:
answer <- confirmDialog frame "Random" "Generate a random number?" True
when answer $ getStdRandom (randomR (1,100)) >>= \num ->
set field [text := show (num :: Int)]</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 1,278 ⟶ 1,385:
This example uses the Unicon gui library, and so will not work in Icon.
 
<syntaxhighlight lang="unicon">
<lang Unicon>
import gui
$include "guih.icn"
Line 1,386 ⟶ 1,493:
w.show_modal ()
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
{{works with|J 8.x}}
<langsyntaxhighlight lang="j">INTERACT=: noun define
pc interact;
cc Value edit center;
Line 1,420 ⟶ 1,527:
wd 'set Value text ' , ": ?100
end.
)</langsyntaxhighlight>
{{works with|J 6.x}}
<langsyntaxhighlight lang="j">INTERACT=: 0 : 0
pc interact closeok;
xywh 6 6 48 12;cc Value edit;
Line 1,453 ⟶ 1,560:
wd 'set Value ' , ": ?100
end.
)</langsyntaxhighlight>
 
Note: I used an edit box for the value, and edit boxes do not get onChange events, so rejection of non-numeric values will be delayed until the use of a button (or pressing enter).
Line 1,459 ⟶ 1,566:
Example use:
 
<syntaxhighlight lang ="j">interact_run''</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,465 ⟶ 1,572:
{{works with|AWT}}
There are nice GUI editors in some IDEs (Netbeans has a notoriously good one), but this GUI was not built automatically, so it's a little easier to understand.
<langsyntaxhighlight lang="java">import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Line 1,557 ⟶ 1,664:
new Interact().setVisible(true);
}
}</langsyntaxhighlight>
{{works with|Java|8+}}
<langsyntaxhighlight lang="java5">import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
Line 1,587 ⟶ 1,694:
public void keyReleased(KeyEvent event);
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="java5">import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
Line 1,778 ⟶ 1,885:
;
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">#=
The task: For a minimal "application", write a program that
presents a form with three components to the user: A numeric input
field ("Value") and two buttons ("increment" and "random").
=#
 
using Tk
 
w = Toplevel("Component Interaction Example")
fr = Frame(w)
pack(fr, {:expand=>true, :fill => "both"})
## The task: For a minimal "application", write a program that
## presents a form with three components to the user: A numeric input
## field ("Value") and two buttons ("increment" and "random").
 
value = Entry(fr, "")
Line 1,800 ⟶ 1,910:
set_value(value, "0") ## The field is initialized to zero.
 
incrementvalue(s) = (val = parse(Int, get_value(value)); set_value(value, string(val + 1)))
tk_bind(increment, "command") do path ## increment its value with the "increment" button.
bind(increment, "command", incrementvalue)
val = get_value(value) | float
set_value(value, string(val + 1))
end
 
 
function validate_command(path, P)
try
if length(P) > 0 parsefloat&& parse(Float64, P) end
tcl("expr", "TRUE")
catch e
Line 1,818 ⟶ 1,925:
tcl(W, "delete", "@0", "end")
end
tk_configure(value, {:validate=>"key", :validatecommand=>validate_command, :invalidcommand=>invalid_command })
 
"""
## Pressing the "random" button presents a confirmation dialog, and resets the field's value to a random value if the answer is "Yes".
Pressing the "random" button presents a confirmation dialog and
tk_bind(random, "command") do path
resets the field's value to a random value if the answer is "Yes".
out = Messagebox(w, "Randomize input", "Select a new random number?")
"""
if out == "ok"
function randval(s)
new_value = floor(100*rand(1))[1]
out = Messagebox(w, title="Randomize input", detail="Select a new random number?")
set_value(value, string(new_value))
if out == "ok"
end
new_value = rand(collect(1:99))
set_value(value, string(new_value))
end
end
bind(random, "command", randval)
</lang>
 
while true sleep(1); end
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
 
<langsyntaxhighlight lang="scala">import java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
Line 1,884 ⟶ 1,995:
fun main(args : Array<String>) {
Interact().isVisible = true
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
 
See http://lambdaway.free.fr/lambdawalks/?view=interaction
 
<syntaxhighlight lang="scheme">
{input {@ id="input" type="text" value="0"}}
{input {@ type="button" value="increment"
onclick="document.getElementById('input').value =
parseInt( document.getElementById('input').value ) + 1;"}}
{input {@ type="button" value="random"
onclick="if (confirm( 'yes?' ))
document.getElementById('input').value =
Math.round(Math.random()*100);"}}
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
===Input Verification===
<langsyntaxhighlight lang="lb">nomainwin
textbox #demo.val, 20, 50, 90, 24
button #demo.inc, "Increment", [btnIncrement], UL, 20, 90, 90, 24
Line 1,943 ⟶ 2,069:
#demo.val nVal
end if
wait</langsyntaxhighlight>
 
===Impossible to type non-numeric characters===
<langsyntaxhighlight lang="lb">nomainwin
stylebits #demo.val, _ES_NUMBER, 0, 0, 0
textbox #demo.val, 20, 50, 90, 24
Line 1,972 ⟶ 2,098:
#demo.val nVal
end if
wait</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,978 ⟶ 2,104:
Version 2, addition a title for form (without title, default title if form variable name, form1).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Declare form1 form
Line 2,026 ⟶ 2,152:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
For this problem, you will need to open up Maple, go to the Components tab on the left, and insert a Text Area, and 2 Buttons. By right clicking each button, and clicking Component Properties, change one to Increase, and the other to Random. Then, click on 'Edit Content Changed Action". In the one labeled increase, type:
 
<syntaxhighlight lang="maple">
<lang Maple>
Increase();
</syntaxhighlight>
</lang>
 
In the one labeled Random, type:
 
<syntaxhighlight lang="maple">
<lang Maple>
Random();
</syntaxhighlight>
</lang>
 
Then, by clicking the 2 gears and opening up the start-up commands, enter this:
<syntaxhighlight lang="maple">
<lang Maple>
macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty);
with(Maplets[Elements]):
Line 2,057 ⟶ 2,183:
end if;
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="text">Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &},
Row@{Button["increment", value++],
Button["random",
Line 2,067 ⟶ 2,193:
Row@{Button["Yes", DialogReturn[True]],
Button["No", DialogReturn[False]]}}],
value = RandomInteger@10000], Method -> "Queued"]}]</langsyntaxhighlight>
 
=={{header|Nim}}==
===Gtk2===
{{libheader|Gtk2}}
<langsyntaxhighlight lang="nim">import
gtk2, gdk2, glib2, strutils, mathrandom
 
import
gtk2, gdk2, glib2, strutils, math
var valu: int = 0
var chngd_txt_hndler: gulong = 0
proc thisDestroy(widget: PWidget, data: Pgpointer) {.cdecl.} =
Line 2,107 ⟶ 2,229:
proc on_question_clicked: bool =
var dialog = win.message_dialog_new(0, MESSAGE_QUESTION,
BUTTONS_YES_NO, "Use a Random number?")
var response = dialog.run()
result if= response == RESPONSE_YES:
dialog.destroy()
result = true
elif response == RESPONSE_NO:
result = false
dialog.destroy()
proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =
Line 2,122 ⟶ 2,241:
proc thisRnd(widget: PWidget, data: Pgpointer){.cdecl.} =
if on_question_clicked():
valu = randomrand(20)
entry_fld.set_text($valu)
proc thisTextChanged(widget: PWidget, data: Pgpointer) {.cdecl.} =
#signal_handler_block(entry_fld, chngd_txt_hndler)
try:
valu = parseInt($entry_fld.get_text())
except EInvalidValueValueError:
entry_fld.set_text($valu = 0)
 
entry_fld.set_text($valu)
#signal_handler_unblock(entry_fld, chngd_txt_hndler)
#signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0)
discard signal_connect(win, "destroy", SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil)
discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil)
discard signal_connect(btn_rnd, "clicked", SIGNAL_FUNC(thisRnd), nil)
chngd_txt_hndler =discard signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil)
win.show_all()
main()</langsyntaxhighlight>
 
===Gtk3 (gintro)===
{{libheader|gintro}}
This is a translation of the Gtk2 version to Gtk3 using the higher level "gintro" bindings. The higher level is not really obvious in this small example, but, for instance, we are able to transmit to signal handlers a pure Nim “Context” object (managed by the GC). With the Gtk2 bindings, it would require to use unsafe addresses.
<syntaxhighlight lang="nim">import random, strutils
import gintro/[glib, gobject, gtk, gio]
 
type Context = ref object
value: int
entry: Entry
 
#---------------------------------------------------------------------------------------------------
 
proc onQuestionClicked(): bool =
 
# As "gintro" doesn't provide "MessageDialog" yet, we will use a simple dialog.
let dialog = newDialog()
dialog.setModal(true)
let label = newLabel("Use a Random number?")
dialog.contentArea.add(label)
discard dialog.addButton("No", ord(ResponseType.no))
discard dialog.addButton("Yes", ord(ResponseType.yes))
dialog.showAll()
result = dialog.run() == ord(ResponseType.yes)
dialog.destroy()
 
#---------------------------------------------------------------------------------------------------
 
proc onQuit(button: Button; window: ApplicationWindow) =
window.destroy()
 
#---------------------------------------------------------------------------------------------------
 
proc onIncr(button: Button; ctx: Context) =
inc ctx.value
ctx.entry.setText($ctx.value)
 
#---------------------------------------------------------------------------------------------------
 
proc onRand(button: Button; ctx: Context) =
if onQuestionClicked():
ctx.value = rand(20)
ctx.entry.setText($ctx.value)
 
#---------------------------------------------------------------------------------------------------
 
proc onEntryChange(entry: Entry; ctx: Context) =
try:
ctx.value = entry.text().parseInt()
except ValueError:
entry.setText($ctx.value)
 
#---------------------------------------------------------------------------------------------------
 
proc activate(app: Application) =
## Activate the application.
 
let window = app.newApplicationWindow()
window.setTitle("Component interaction")
 
let content = newBox(Orientation.vertical, 10)
content.setHomogeneous(true)
let hbox1 = newBox(Orientation.horizontal, 10)
hbox1.setHomogeneous(true)
let hbox2 = newBox(Orientation.horizontal, 1)
hbox2.setHomogeneous(false)
let label = newLabel("Value:")
let entry = newEntry()
entry.setText("0")
let btnQuit = newButton("Quit")
let btnIncr = newButton("Increment")
let btnRand = newButton("Random")
 
hbox2.add(label)
hbox2.add(entry)
hbox1.add(btnIncr)
hbox1.add(btnRand)
 
content.packStart(hbox2, true, true, 0)
content.packStart(hbox1, true, true, 0)
content.packStart(btnQuit, true, true, 0)
 
window.setBorderWidth(5)
window.add(content)
 
let context = Context(value: 0, entry: entry)
 
discard btnQuit.connect("clicked", onQuit, window)
discard btnIncr.connect("clicked", onIncr, context)
discard btnRand.connect("clicked", onRand, context)
discard entry.connect("changed", onEntryChange, context)
 
window.showAll()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
let app = newApplication(Application, "Rosetta.ComponentInteraction")
discard app.connect("activate", activate)
discard app.run()</syntaxhighlight>
 
===IUP===
{{libheader|IUP}}
<langsyntaxhighlight lang="nim">import
iup, strutils, math
 
Line 2,208 ⟶ 2,422:
discard dlg.show()
discard mainloop()
iup.close()</langsyntaxhighlight>
 
=={{header|Oz}}==
Using Mozart's standard GUI library, building a small desktop application:
<langsyntaxhighlight lang="oz">declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
 
Line 2,253 ⟶ 2,467:
end
in
{Main}</langsyntaxhighlight>
 
As a web application, using the "Roads" web programming library. Connect your browser to http://localhost:8080/start after starting the program.
<langsyntaxhighlight lang="oz">declare
[Roads] = {Module.link ['x-ozlib://wmeyer/roads/Roads.ozf']}
 
Line 2,311 ⟶ 2,525:
in
{Roads.registerFunction 'start' Start}
{Roads.run}</langsyntaxhighlight>
 
=={{header|PhixPerl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
{{libheader|Phix/pGUI}}
<lang Phix>include pGUI.e
 
use strict;
Ihandle txt, increment, random, hbx, vbx, dlg
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
 
my $value = 0;
function action_cb(Ihandle /*ih*/, integer ch)
if not find(ch,"0123456789-") then return IUP_IGNORE end if
return IUP_CONTINUE
end function
 
my $mw = MainWindow->new;
function increment_cb(Ihandle /*ih*/)
$mw->title( 'GUI component interaction' );
integer v = IupGetInt(txt,"VALUE")+1
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
IupSetInt(txt,"VALUE",v)
$lf->Entry( -width => 10, -textvariable => \$value,
return IUP_CONTINUE
-validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ },
end function
)->pack(-fill => 'x', -expand => 1);
$mw->Button( -text => 'increment', -command => sub { $value++ },
)->pack( -side => 'left' );
$mw->Button( -text => 'random', -command => sub {
$mw->Dialog(
-text => 'Change to a random value?',
-title => 'Confirm',
-buttons => [ qw(Yes No) ]
)->Show eq 'Yes' and $value = int rand 1e9; }
)->pack( -side => 'right' );
 
MainLoop;</syntaxhighlight>
function random_cb(Ihandle /*ih*/)
if IupAlarm("Confirm","Replace wth random value?","Yes","No")=1 then
IupSetInt(txt,"VALUE",rand(1000))
end if
return IUP_CONTINUE
end function
 
=={{header|Phix}}==
IupOpen()
{{libheader|Phix/basics}}
txt = IupText(Icallback("action_cb"),"EXPAND=YES")
{{libheader|Phix/pGUI}}
increment = IupButton("increment",Icallback("increment_cb"))
<!--<syntaxhighlight lang="phix">-->
random = IupButton("random",Icallback("random_cb"))
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20")
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">increment</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">random</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hbx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">vbx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
dlg = IupDialog(vbx)
IupCloseOnEscape(dlg)
<span style="color: #008080;">function</span> <span style="color: #000000;">action_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
IupShow(dlg)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0123456789-"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_IGNORE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
IupMainLoop()
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
IupClose()</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">increment_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">random_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">IupAlarm</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Confirm"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Replace wth random value?"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Yes"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"No"</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"action_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"EXPAND=YES"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">increment</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"increment"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"increment_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">random</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"random"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"random_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">hbx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">increment</span><span style="color: #0000FF;">,</span><span style="color: #000000;">random</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=0x10, GAP=20"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">vbx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hbx</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=40x20"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vbx</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
The standard PicoLisp GUI is HTTP based. Connect your browser to
http://localhost:8080 after starting the following script.
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
Line 2,369 ⟶ 2,616:
 
(server 8080 "!start")
(wait)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">[xml]$XML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Rosetta Code" WindowStartupLocation = "CenterScreen" Height="100" Width="210" ResizeMode="NoResize">
Line 2,396 ⟶ 2,643:
$buttonIncrement.add_click({++[Int]$textBoxValue.Text})
 
$XMLForm.ShowDialog() | Out-Null</langsyntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<langsyntaxhighlight Prologlang="prolog">dialog('GUI_Interaction',
[ object :=
GUI_Interaction,
Line 2,481 ⟶ 2,728:
( send(@display, inform, 'Please type a number !'),
send(Input,clear))).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#StringGadget
#Increment
Line 2,511 ⟶ 2,758:
Until Event=#PB_Event_CloseWindow
CloseWindow(0)
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,518 ⟶ 2,765:
{{libheader|Tkinter}}
{{works with|Python|2.7}}
<langsyntaxhighlight lang="python">
import random, tkMessageBox
from Tkinter import *
Line 2,542 ⟶ 2,789:
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()</langsyntaxhighlight>
 
===Python3 - no classes===
{{libheader|Tkinter}}
{{works with|Python|3.7}}
<langsyntaxhighlight lang="python">
import random, tkinter.messagebox
from tkinter import *
Line 2,576 ⟶ 2,823:
b2.grid(column=2, row=0, **options)
 
mainloop()</langsyntaxhighlight>
 
===Python2 - With classes===
{{libheader|Tkinter}}
<langsyntaxhighlight lang="python">import random
from Tkinter import *
import tkMessageBox
Line 2,632 ⟶ 2,879:
app.mainloop()
except KeyboardInterrupt:
root.destroy()</langsyntaxhighlight>
 
[[File:GUI_component_interaction_Python.png]]
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
Line 2,668 ⟶ 2,915:
svalue(e) <- sample(1:1000, 1)
})
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket/gui
Line 2,697 ⟶ 2,944:
 
(send frame show #t)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,704 ⟶ 2,951:
{{libheader|GTK}}
 
<syntaxhighlight lang="raku" perl6line>use GTK::Simple;
use GTK::Simple::App;
 
Line 2,737 ⟶ 2,984:
}
 
$app.run;</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 2,772 ⟶ 3,019:
num = string(number(num)+1)
lineedit1.settext(num)
</syntaxhighlight>
</lang>
 
Output:
Line 2,780 ⟶ 3,027:
=={{header|Ruby}}==
{{libheader|Shoes}}
<langsyntaxhighlight lang="ruby">Shoes.app(title: "GUI component interaction") do
stack do
textbox = edit_line
Line 2,798 ⟶ 3,045:
end
end
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim dd$(5) ' drop down box
for i = 1 to 5
dd$(i) = "Drop ";i
Line 2,843 ⟶ 3,090:
[exit]
print "Bye"
end</langsyntaxhighlight>
[[File:GuiComponentRunBasic.png]]
 
== {{Header|Rust}} ==
{{libheader|egui}}
<syntaxhighlight lang="rust">
use eframe::egui;
use rand::Rng;
 
fn main() -> Result<(), eframe::Error> {
let options = eframe::NativeOptions {
initial_window_size: Some(egui::vec2(214.0, 100.0)),
..Default::default()
};
 
// Our application state:
let mut value = "0".to_owned();
 
eframe::run_simple_native("GUI component interaction", options, move |ctx, _frame| {
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
let name_label = ui.label("Value: ");
ui.text_edit_singleline(&mut value)
.labelled_by(name_label.id);
});
ui.horizontal(|ui| {
if ui.button("Increment").clicked() {
if let Ok(v) = value.parse::<usize>() {
value = (v + 1).to_string()
}
}
if ui.button("Random").clicked() {
value = (rand::thread_rng().gen_range(1..=10000)).to_string();
}
});
});
})
}</syntaxhighlight>
[[File:Rust GUI component interaction.png|none|thumb]]
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import scala.swing._
import scala.swing.Swing._
import scala.swing.event._
Line 2,891 ⟶ 3,175:
centerOnScreen()
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|top input vh incButton rndButton|
 
vh := ValueHolder with:0.
Line 2,912 ⟶ 3,196:
rndButton action:[ vh value: Random nextInteger ].
 
top open</langsyntaxhighlight>
{{Out}}
[[File:Guiintsmalltalkx.png]]
Line 2,918 ⟶ 3,202:
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
###--- Our data Model! ---###
Line 2,952 ⟶ 3,236:
set field [expr {int(rand() * 5000)}]
}
}</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gtk+-3.0}}
 
<langsyntaxhighlight lang="vala">bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
Line 2,981 ⟶ 3,265:
window.window_position = Gtk.WindowPosition.CENTER;
window.destroy.connect(Gtk.main_quit);
window.set_default_size(0,0);
 
 
Line 3,037 ⟶ 3,322:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
Line 3,045 ⟶ 3,330:
Note that there are other methods of validating the entered value. The method used is dependant on the program's requirements.
 
<langsyntaxhighlight lang="vb">VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
Line 3,106 ⟶ 3,391:
KeyAscii = 0
End Select
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
Graphical
 
Notes:
 
1) "v install ui" to get, also to locally check source and examples.
 
2) For alternative UI toolkits, check github.com/vlang/awesome-v (Awesome V).
<syntaxhighlight lang="Zig">
import ui
import gx
import rand
 
const (
win_width = 400
win_height = 40
)
 
[heap]
struct App {
mut:
window &ui.Window = unsafe {nil}
counter string = "0"
}
 
fn main() {
mut app := &App{}
app.window = ui.window(
width: win_width
height: win_height
title: "Counter"
mode: .resizable
layout: ui.row(
spacing: 5
margin_: 10
widths: ui.stretch
heights: ui.stretch
children: [
ui.textbox(
max_len: 20
read_only: false
// is_numeric: true // Can enforce only number input
text: &app.counter
),
ui.button(
text: "increment"
bg_color: gx.light_gray
radius: 5
border_color: gx.gray
on_click: app.btn_click_inc
),
ui.button(
text: "random"
bg_color: gx.light_gray
radius: 5
border_color: gx.gray
on_click: app.btn_click_ran
),
]
)
)
ui.run(app.window)
}
 
fn (mut app App) btn_click_inc(mut btn ui.Button) {
for value in app.counter {
if value.is_digit() == false {
ui.message_box("Only numbers allowed!")
return
}
}
if app.counter.int() < 0 || app.counter.int() > 100 {
ui.message_box("Only numbers between 0 to 100 accepted!\nResetting to 1.")
app.counter = "0"
}
app.counter = (app.counter.int() + 1).str()
}
 
fn (mut app App) btn_click_ran(mut btn ui.Button) {
ui.message_box("Will jump to random number between 1 and 100.")
app.counter = rand.int_in_range(1, 100) or {0}.str()
}
</syntaxhighlight>
 
=={{header|Web 68}}==
Web 68 uses an include file to use the Xforms library.
<langsyntaxhighlight lang="web68">@1Rosetta code program.
@aPROGRAM guicomponent CONTEXT VOID USE standard
BEGIN
Line 3,239 ⟶ 3,608:
macro fl show form;
 
@ The end.</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
{{libheader|Wren-polygon}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "random" for Random
import "./polygon" for Polygon
 
var Rand = Random.new()
 
class Button {
construct new(x, y, w, h, legend, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_legend = legend
_c = c
_oc = oc
_lc = lc
}
 
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_legend)
var lx = ((_w - l.x)/2).truncate
lx = (lx > 0) ? _x + lx : _x + 1
var ly = ((_h - l.y)/2).truncate
ly = (ly > 0) ? _y + ly : _y + 1
Canvas.print(_legend, lx, ly, _lc)
}
 
justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) }
}
 
class TextBox {
construct new(x, y, w, h, label, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_label = label
_c = c
_oc = oc
_lc = lc
_text = ""
}
 
text { _text }
text=(t) { _text = t }
 
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_label).x
var lx = _x - l - 7
if (lx < 1) {
lx = 1
_label = _label[0..._x]
}
Canvas.print(_label, lx, _y, _lc)
Canvas.getPrintArea(_label).x
Canvas.print(_text, _x + 3, _y + 1, Color.black)
}
}
 
class GUIComponentInteraction {
construct new() {
Window.title = "GUI component interaction"
_btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white)
_btnRandom = Button.new(180, 40, 80, 80, "Random", Color.green, Color.blue, Color.white)
_txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white)
_txtValue.text = "0"
Keyboard.handleText = true
_waiting = false
}
 
init() {
drawControls()
}
 
update() {
if (_waiting) {
if (Keyboard["Y"].justPressed) {
var rn = Rand.int(1000) // max 999 say
_txtValue.text = rn.toString
_waiting = false
} else if (Keyboard["N"].justPressed) {
_waiting = false
}
} else if (_btnIncrement.justClicked) {
var number = Num.fromString(_txtValue.text) + 1
_txtValue.text = number.toString
} else if (_btnRandom.justClicked) {
Canvas.print("Reset to a random number y/n?", 60, 200, Color.white)
_waiting = true
} else if ("0123456789".any { |d| Keyboard[d].justPressed }) {
if (_txtValue.text != "0") {
_txtValue.text = _txtValue.text + Keyboard.text
} else {
_txtValue.text = Keyboard.text
}
}
}
 
draw(alpha) {
if (!_waiting) drawControls()
}
 
drawControls() {
Canvas.cls()
_btnIncrement.draw()
_btnRandom.draw()
_txtValue.draw()
}
}
 
var Game = GUIComponentInteraction.new()</syntaxhighlight>
Anonymous user