GUI component interaction: Difference between revisions

m
imported>Arakov
 
(92 intermediate revisions by 37 users not shown)
Line 6:
{{omit from|Blast}}
{{omit from|Brainf***}}
{{omit from|Commodore BASIC}}
{{omit from|GUISS|Only makes use of installed applications}}
{{omit from|Integer BASIC|no concept of a GUI}}
Line 12 ⟶ 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 26 ⟶ 32:
* pop up dialogs to query the user for further information
 
 
The task: For a minimal "application", write a program that presents
;Task:
a form with three components to the user:
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").
::* a numeric input field ("Value")
::* a button ("increment")
::* a button ("random")
 
 
The field is initialized to zero.
 
The user may manually enter a new value into the field,
or increment its value with the "increment" button.
 
Entering a non-numeric value should be either impossible,
or issue an error message.
Line 39 ⟶ 51:
and resets the field's value to a random value if the answer is "Yes".
 
(This task may be regarded as an extension of the task [[Simple windowed application]]).<br><br>
 
=={{header|1C}}==
<syntaxhighlight lang="text">
&НаСервере
Процедура ДобавитьЭлементы()
КЧ = Новый КвалификаторыЧисла(12,2);
Массив = Новый Массив;
Массив.Добавить(Тип("Число"));
ОписаниеТиповЧ = Новый ОписаниеТипов(Массив, , ,КЧ);
НовыйРеквизит = Новый РеквизитФормы("ВводимоеЧисло", Новый ОписаниеТипов(Массив, , ,КЧ));;
 
МассивР = Новый Массив;
МассивР.Добавить(НовыйРеквизит);
ИзменитьРеквизиты(МассивР);
ПолеВвода = Элементы.Добавить("ПолеВвода", Тип("ПолеФормы"));
ПолеВвода.ПутьКДанным = "ВводимоеЧисло";
ПолеВвода.вид = ВидПоляФормы.ПолеВвода;
КомандаИнкримент = Команды.Добавить("Инкримент");
КомандаРандом = КОманды.Добавить("Рандом");
КнопкаИнкримент = Элементы.Добавить("КнопкаИнкримент", Тип("КнопкаФормы"));
КнопкаИнкримент.ИмяКоманды = "Инкримент";
КнопкаРандом = Элементы.Добавить("КнопкаРандом", Тип("КнопкаФормы"));
КнопкаРандом.ИмяКоманды = "Рандом";
 
КомандаИнкримент.Действие = "Инкримент";
КомандаРандом.Действие = "Рандом";
КонецПроцедуры
 
&НаКлиенте
Процедура Инкримент(Команда)
ЭтотОбъект.ВводимоеЧисло = ЭтотОбъект.ВводимоеЧисло + 1;
КонецПроцедуры
 
&НаКлиенте
Процедура Рандом(Команда)
ОписаниеОповещения = Новый ОписаниеОповещения("РандомПослеВыбора", ЭтотОбъект);
ПоказатьВопрос(ОписаниеОповещения, "Установить случайное число?", РежимДиалогаВопрос.ДаНет);
КонецПроцедуры
 
&НаКлиенте
Процедура РандомПослеВыбора(РезультатВопроса, ДополнительныеПараметры) Экспорт
Если РезультатВопроса = КодВозвратаДиалога.Да Тогда
ГСЧ = Новый ГенераторСлучайныхЧисел();
ЭтотОбъект.ВводимоеЧисло = ГСЧ.СлучайноеЧисло(0, 999999);
КонецЕсли;
КонецПроцедуры
</syntaxhighlight>
 
=={{header|Ada}}==
Line 45 ⟶ 119:
 
interaction.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Gtk.Main;
Line 202 ⟶ 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 259 ⟶ 333:
ExitApp ; Makes sure the script exits when the window is closed,
; Otherwise the script is persistent because it contains
; a timer.</langsyntaxhighlight>
 
=={{header|BBC 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 292 ⟶ 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>
<p>
 
[[File:Guiintbbc.gif]]
=={{header|C}}==
{{works with|C (with Win32 API)}}
 
<pre>file main.c</pre>
 
<syntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {
switch( msg ) {
 
case WM_INITDIALOG:
srand( GetTickCount() );
SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );
break;
 
case WM_COMMAND:
switch( LOWORD(wPar) ) {
case IDC_INCREMENT: {
UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );
SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );
} break;
case IDC_RANDOM: {
int reply = MessageBox( hwnd,
"Do you really want to\nget a random number?",
"Random input confirmation", MB_ICONQUESTION|MB_YESNO );
if( reply == IDYES )
SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );
} break;
case IDC_QUIT:
SendMessage( hwnd, WM_CLOSE, 0, 0 );
break;
default: ;
}
break;
 
case WM_CLOSE: {
int reply = MessageBox( hwnd,
"Do you really want to quit?",
"Quit confirmation", MB_ICONQUESTION|MB_YESNO );
if( reply == IDYES )
EndDialog( hwnd, 0 );
} break;
 
default: ;
}
 
return 0;
}
 
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {
return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );
}</syntaxhighlight>
 
<pre>file resource.h</pre>
 
<syntaxhighlight lang="c">#define IDD_DLG 101
#define IDC_INPUT 1001
#define IDC_INCREMENT 1002
#define IDC_RANDOM 1003
#define IDC_QUIT 1004</syntaxhighlight>
 
<pre>file resource.rc</pre>
 
<syntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
IDD_DLG DIALOG 0, 0, 154, 46
STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION |
WS_VISIBLE | WS_POPUP | WS_SYSMENU
CAPTION "GUI Component Interaction"
FONT 12, "Ms Shell Dlg" {
EDITTEXT IDC_INPUT, 7, 7, 140, 12, ES_AUTOHSCROLL | ES_NUMBER
PUSHBUTTON "Increment", IDC_INCREMENT, 7, 25, 50, 14
PUSHBUTTON "Random", IDC_RANDOM, 62, 25, 50, 14
PUSHBUTTON "Quit", IDC_QUIT, 117, 25, 30, 14
}</syntaxhighlight>
 
=={{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 321 ⟶ 513:
void findRandomNumber( ) ;
} ;
#endif</langsyntaxhighlight>
<pre>file interaction.cpp</pre>
<langsyntaxhighlight lang="cpp">#include <QPushButton>
#include <QLineEdit>
#include <QMessageBox>
Line 370 ⟶ 562:
break ;
}
}</langsyntaxhighlight>
<pre>file main.cpp </pre>
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include "interaction.h"
 
Line 380 ⟶ 572:
theWidget.show( ) ;
return app.exec( ) ;
}</langsyntaxhighlight>
 
===C++11===
Line 387 ⟶ 579:
<pre>main.cpp</pre>
 
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
Line 432 ⟶ 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 509 ⟶ 701:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{libheader|LTK}}
<langsyntaxhighlight lang="lisp">
;; Using the LTK library...
 
Line 553 ⟶ 746:
(gui-test)
 
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
 
<syntaxhighlight lang Delphi="delphi">FILE: Unit1.pas</langsyntaxhighlight>
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Unit1;
 
Line 588 ⟶ 782:
 
procedure TForm1.EditInputFieldChange(Sender: TObject);
Var
Value: Integer;
begin
if not TryStrToInt(EditInputField.Text, value) then
TRY
begin
StrToInt(EditInputField.Text);
ShowMessage('Error! The Input Value is not numeric!');
EXCEPT
ShowMessage('Error! The Input Value is not numeric!');
EditInputField.Text := '0';
ENDend;
end;
 
procedure TForm1.ButtonIncrementClick(Sender: TObject);
begin
EditInputField.text := IntToStr (StrToInt(EditInputField.Text) + 1);
end;
 
Line 608 ⟶ 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 654 ⟶ 849:
end
end
</syntaxhighlight>
</lang>
 
=={{header|ElenaEcholisp}}==
<syntaxhighlight lang="scheme">
<lang elena>#import system.
(require 'interface)
#import forms.
#import extensions.
 
;; helper new button with text
#class Window
(define (ui-add-button text)
(define b (ui-create-element "button" '((type "button"))))
(ui-set-html b text)
(ui-add b))
 
 
(define (panel )
(ui-clear)
(info-text "My rosetta application" "blue")
 
;; input field (checked for numeric)
(define f-input (ui-create-element "input" '((type number))))
(ui-set-value f-input 0)
(ui-add f-input)
(ui-on-focus f-input (lambda(e) (info-text "")))
;; Increment button
(define btn-inc (ui-add-button "Increment"))
(define (increment elem)
(define val (ui-get-numvalue f-input))
(if val ;; checked legal numeric
(ui-set-value f-input (1+ val))
(info-text "Need a number" "red")))
(ui-on-click btn-inc increment)
(ui-add btn-inc)
 
(define btn-random (ui-add-button "Random"))
(define (set-random elem)
(when (confirm "Really random?")
(ui-set-value f-input (random-prime 1000000))))
(ui-on-click btn-random set-random)
 
(ui-focus btn-inc)
(stdout-hide #t)
(stdin-hide #t)) ;; end panel
 
(panel)
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import forms;
import extensions;
public class MainWindow : SDIDialog
{
Button btmIncrement;
#field form.
Button btmRandom;
#field btmIncrement.
Edit txtNumber;
#field btmRandom.
#field txtNumber.
constructor new()
<= super new()
#field number.
{
btmIncrement := Button.new();
#constructor new
[ btmRandom := Button.new();
txtNumber form := SDIDialog newEdit.new();
btmIncrement := Button new.
self
btmRandom := Button new.
.appendControl(btmIncrement)
txtNumber := Edit new.
.appendControl(btmRandom)
number := 0.appendControl(txtNumber);
 
self.Caption := form controls"Rosseta Code";
self.setRegion(100, 100, 180, 140);
+= btmIncrement
+= btmRandom
txtNumber.setRegion(20, 7, 140, 25);
+= txtNumber.
txtNumber.Caption := "0";
form set &caption:"Rosseta Code".
btmIncrement.setRegion(20, 35, 140, 25);
form set &x:100 &y:100.
btmIncrement.Caption := "Increment";
form set &width:160 &height:120.
btmIncrement.onClick := (args){ self.onButtonIncrementClick() };
txtNumber set &x:7 &y:7.
btmRandom.setRegion(20, 65, 140, 25);
txtNumber set &width:140 &height:25.
btmRandom.Caption := "Random";
txtNumber set &caption:(number literal).
btmRandom.onClick := (args){ self.onButtonRandomClick() };
}
btmIncrement set &x:7 &y:35.
btmIncrement set &width:140 &height:25.
private onButtonIncrementClick()
btmIncrement set &caption:"Increment".
{
btmIncrement set &onClick:args
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.nextInt(99999999))
}
}
private changeTextBoxValue(number)
{
txtNumber.Caption := number.toString()
}
}</syntaxhighlight>
 
=={{header|Euphoria}}==
[ $self $onButtonIncrementClick. ].
<syntaxhighlight lang="euphoria">
include GtkEngine.e -- see OpenEuphoria.org
btmRandom set &x:7 &y:65.
btmRandom set &width:140 &height:25.
btmRandom set &caption:"Random".
btmRandom set &onClick:args
 
constant -- interface
[ $self $onButtonRandomClick. ].
win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"),
]
pan = create(GtkBox,"orientation=vertical;spacing=10"),
inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"),
box = create(GtkButtonBox),
btn1 = create(GtkButton,"gtk-add#_Increment","Increment"),
btn2 = create(GtkButton,"gtk-help#_Random","Random")
add(win,pan)
#method $onButtonIncrementClick
add(pan,inp)
[
add(box,{btn1,btn2})
number := number + 1.
pack(pan,-box)
$self $changeTextBoxValue.
 
]
show_all(win)
main()
#method $onButtonRandomClick
[
-----------------------------
(messageDialog open &caption:"Inf" &question:"Really reset to random value?")?
global function Validate() -- warns about invalid entry, does not prevent it;
[
-----------------------------
number := randomGenerator eval:99999999.
if not t_digit(trim_head(get("Input.text"),"- ")) then
$self $changeTextBoxValue.
return Warn(win,"Validate","This is not a valid number","Try again!")
].
end if
]
return 1
end function
#method $changeTextBoxValue
 
[
---------------------------
txtNumber set &caption:(number literal).
global function Increment()
]
---------------------------
set("Input.value",get("Input.value")+1)
#method => form.
return 1
}</lang>
end function
 
------------------------
global function Random()
------------------------
if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then
set("Input.value",rand(1000))
end if
return 1
end function
 
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// GUI component interaction. Nigel Galloway: June 13th., 2020
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")
let l=new System.Windows.Forms.Button(Location=new System.Drawing.Point(135,70),Text="Random")
n.Controls.AddRange([|i;g;e;l|])
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))))
l.Click.AddHandler(new System.EventHandler(fun _ _->i.Text<-(string(rand.Next()))))
System.Windows.Forms.Application.Run(n)
</syntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
using fwt
using gfx
Line 798 ⟶ 1,085:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#Include "windows.bi"
 
Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Rnd
Dim As MSG msg
Dim As Integer n
Dim As String text
 
'Create a window with an input field and two buttons:
Window_Main = CreateWindow("#32770", "GUI Component Interaction", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 200, 0, 0, 0, 0)
Var Static_Number = CreateWindow("STATIC", "Value:", WS_VISIBLE Or WS_CHILD, 10, 10, 100, 20, Window_Main, 0, 0, 0)
Edit_Number = CreateWindow("EDIT", "0", WS_BORDER Or WS_VISIBLE Or WS_CHILD Or ES_AUTOHSCROLL Or ES_Number, 110, 10, 100, 20, Window_Main, 0, 0, 0)
Button_Inc = CreateWindow("BUTTON", "Increment", WS_VISIBLE Or WS_CHILD, 110, 40, 100, 20, Window_Main, 0, 0, 0)
Button_Rnd = CreateWindow("BUTTON", "Random", WS_VISIBLE Or WS_CHILD, 110, 70, 100, 20, Window_Main, 0, 0, 0)
'Windows message loop:
While GetMessage(@msg, Window_Main, 0, 0)
TranslateMessage(@msg)
DispatchMessage(@msg)
Select Case msg.hwnd
Case Button_Inc
If msg.message = WM_LBUTTONDOWN Then
'Increment value:
text = Space(GetWindowTextLength(Edit_Number) + 1) 'Buffer for the text
GetWindowText(Edit_Number, text, Len(text))
n = Val(text)
SetWindowText(Edit_Number, Str(n + 1))
End If
Case Button_Rnd
If msg.message = WM_LBUTTONDOWN THEN
'Random value (max. 100000):
If MessageBox(0, "Set input field to random value?", "Please confirm", MB_ICONQUESTION Or MB_YESNO) = IDYES Then
n = 100000 * RND
SetWindowText(Edit_Number, Str(n))
End If
End If
Case Window_Main
If msg.message = WM_COMMAND Then End
End Select
Wend
 
End
</syntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="gambas">hValueBox As ValueBox 'We need a ValueBox
 
Public Sub Form_Open()
Dim hButton As Button 'We need 2 Buttons
 
With Me 'Set the Form's Properties..
.height = 95 'Set the Height
.Width = 350 'Set the Width
.Arrangement = Arrange.Vertical 'Arrange items vertically
.Padding = 5 'Border area
.Title = "GUI component interaction" 'Title displayed on the Form
End With
 
hValueBox = New ValueBox(Me) 'Add a ValueBox to the Form
 
With hValueBox 'Set the ValueBox's Properties..
.Expand = True 'Expand the ValueBox
.Value = 0 'Set it's value to 0
End With
 
hButton = New Button(Me) As "ButtonInc" 'Add a Button to the form as Event "ButtonInc"
 
With hButton 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Increment" 'Add Text (The '&' adds a keyboard shortcut)
End With
 
hButton = New Button(Me) As "ButtonRand" 'Add a Button to the form as Event "ButtonRand"
 
With hButton 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Random" 'Add Text (The '&' adds a keyboard shortcut)
End With
 
End
 
Public Sub ButtonInc_Click() 'When the 'Increment' Button is clicked..
 
hValueBox.Value += 1 'Increase the Value in the ValueBox by 1
 
End
 
Public Sub ButtonRand_Click() 'When the 'Random' Button is clicked..
Dim siRand As Short 'To store random number
Dim byAnswer As Byte 'To store the answer to the MessageBox question
 
siRand = Rand(1, 32767) 'Create a 'Random' mnumber
 
byAnswer = Message.Question("Would you like to set the ValueBox to " & siRand & "?", "Yes", "No") ' Ask if the number is OK
If byAnswer = 1 Then 'If the user says 'Yes' then
hValueBox.Value = siRand 'Display the 'Random' number in the ValueBox
Else 'ELSE
hValueBox.Value = 0 'Set the ValueBox Value to 0
End If
 
End</syntaxhighlight>
 
=={{header|Go}}==
{{libheader|gotk3}}
{{trans|Vala}}
<syntaxhighlight lang="go">package main
 
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
 
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
 
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
 
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
 
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
 
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
 
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
 
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0") // initialize to zero
entry.Connect("activate", func() {
// read and validate the entered value
str, _ := entry.GetText()
validateInput(window, str)
})
 
// button to increment
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.Connect("clicked", func() {
// read and validate the entered value
str, _ := entry.GetText()
if i, ok := validateInput(window, str); ok {
entry.SetText(strconv.FormatInt(i+1, 10))
}
})
 
// button to put in a random value if confirmed
rb, err := gtk.ButtonNewWithLabel("Random")
check(err, "Unable to create random button:")
rb.Connect("clicked", func() {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Set random value",
)
answer := dialog.Run()
dialog.Destroy()
if answer == gtk.RESPONSE_YES {
entry.SetText(strconv.Itoa(rand.Intn(10000)))
}
})
 
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(rb, false, false, 2)
window.Add(box)
 
window.ShowAll()
gtk.Main()
}</syntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight Haskelllang="haskell">import Graphics.UI.WX
import System.Random
 
Line 827 ⟶ 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 833 ⟶ 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 941 ⟶ 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 975 ⟶ 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,008 ⟶ 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,014 ⟶ 1,566:
Example use:
 
<syntaxhighlight lang ="j">interact_run''</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,020 ⟶ 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,112 ⟶ 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,142 ⟶ 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,333 ⟶ 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,355 ⟶ 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,373 ⟶ 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 kotlinlang="scala">import java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.*
 
import java.lang.Long // jet.Long doesn't suit our needs here
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JOptionPane
import javax.swing.JPanel
import javax.swing.JTextField
 
class Interact : JFrame() {
Line 1,406 ⟶ 1,956:
val incButton = JButton("Increment")
val randButton = JButton("Random")
val buttonPanel = JPanel();
 
init {
setDefaultCloseOperation(defaultCloseOperation = JFrame.EXIT_ON_CLOSE)
numberField.text setText= "0"
 
numberField .addKeyListener(object : KeyListener {
public override fun keyTyped(e : KeyEvent) : Unit ={
if (!Character.isDigit(e.getKeyChar()keyChar)) e.consume()
public override fun keyReleased(e : KeyEvent?) {}
public override fun keyPressed(e : KeyEvent) {}
});
 
incButton addActionListener(object : ActionListener {
public override fun actionPerformed(e : ActionEvent) {
val num = Long.parseLong(numberField.getText() ?: "")
numberField setText (num + 1).toString()
}
override fun keyReleased(e : KeyEvent?) {}
});
override fun keyPressed(e : KeyEvent) {}
})
 
randButton incButton.addActionListener(object : ActionListener {
val num = (numberField.text ?: "").toDouble()
numberField.text = (num + 1).toString()
}
 
randButton.addActionListener(object : ActionListener {
fun proceedOrNot() = JOptionPane.showConfirmDialog(randButton, "Are you sure?")
public override fun actionPerformed(e : ActionEvent) {
if(proceedOrNot() == JOptionPane.YES_OPTION)
numberField.text setText= Long.toString((Math.random() * Long.MAX_VALUE).toLongtoString())
}
});
 
setLayout(layout = GridLayout(2, 1))
buttonPanel.layout setLayout= GridLayout(1, 2)
buttonPanel .add (incButton)
buttonPanel .add (randButton)
add(numberField)
add(buttonPanel)
Line 1,445 ⟶ 1,994:
 
fun main(args : Array<String>) {
Interact().isVisible = setVisible(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,505 ⟶ 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,534 ⟶ 2,098:
#demo.val nVal
end if
wait</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
M2000 uses twips for positions and width/height of forms and controls. M2000 Environment has a window manager, which used in Windows and Ubuntu (through Wine) operating systems. The window style is the same to every os.
<lang>Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &},
Version 2, addition a title for form (without title, default title if form variable name, form1).
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Declare form1 form
Declare textbox1 textbox form form1
Declare buttonInc Button form form1
Declare buttonRND Button form form1
Method textbox1, "move", 2000,2000,4000,600
Method buttonInc, "move", 2000,3000,2000,600
Method buttonRND, "move", 4000,3000,2000,600
With form1, "Title", "Rosetta Code: GUI component interaction"
With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:", "ShowAlways", true
With buttonInc,"Caption","Increment"
With buttonRND,"Caption","Random"
textbox1.value$="0"
Function Local1(new Feed$) {
\\ this Function can be used from other Integer
\\ this$ and thispos, exist just before the call of this Function
local sgn$
if feed$="" and this$="-" then thispos-- : exit
if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2)
if this$<>Trim$(this$) then this$=Feed$ : thispos-- : exit
If Trim$(this$)="" then this$="0" : thispos=2 : exit
if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$=""
if instr(this$,"-")>0 and sgn$="" then this$=filter$(this$, "-") : sgn$="-"
if filter$(this$,"0123456789")<>"" then this$=Feed$ : thispos-- : exit
if len(this$)>1 then While left$(this$,1)="0" {this$=mid$(this$, 2)}
this$=sgn$+this$
if this$="-0" then this$="-" : thispos=2
}
Function TextBox1.ValidString {
\\ this Function called direct from textbox
Read New &this$, &thispos
Call Local local1(textbox1.value$)
}
Function buttonInc.Click {
textbox1.value$=str$(val(textbox1.value$)+1, "")
}
Function buttonRND.Click {
If AsK$("Change Value with random number", "Question", "Yes", "No")="Yes" Then {
textbox1.value$=str$(Random(0, 10000), "")
After 100 {Try {Method textbox1,"GetFocus"}}
}
}
\\ open modal
Method form1, "show", 1
Declare form1 nothing
}
Checkit
</syntaxhighlight>
 
=={{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">
Increase();
</syntaxhighlight>
 
In the one labeled Random, type:
 
<syntaxhighlight lang="maple">
Random();
</syntaxhighlight>
 
Then, by clicking the 2 gears and opening up the start-up commands, enter this:
<syntaxhighlight lang="maple">
macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty);
with(Maplets[Elements]):
SP("Text",value,0);
Increase:=proc()
SP("Text",value,parse(GP("Text",value))+1);
end proc;
Random:=proc()
maplet := Maplet(["Are you sure?", [Button("OK", Shutdown("true")), Button("Cancel", Shutdown())]]);
result := Maplets[Display](maplet);
if result = "true" then
j:=rand(1..1000);
SP("Text",value,j());
end if;
end proc;
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="text">Manipulate[Null, {{value, 0}, InputField[Dynamic[value], Number] &},
Row@{Button["increment", value++],
Button["random",
Line 1,544 ⟶ 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 1,584 ⟶ 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 1,599 ⟶ 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 1,685 ⟶ 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 1,730 ⟶ 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 1,788 ⟶ 2,525:
in
{Roads.registerFunction 'start' Start}
{Roads.run}</langsyntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
 
my $value = 0;
 
my $mw = MainWindow->new;
$mw->title( 'GUI component interaction' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
$lf->Entry( -width => 10, -textvariable => \$value,
-validate => 'key', -validatecommand => sub { $_[0] =~ /^\d{1,9}\z/ },
)->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>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<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>
<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>
<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>
<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;">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 1,810 ⟶ 2,616:
 
(server 8080 "!start")
(wait)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">[xml]$XML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Rosetta Code" WindowStartupLocation = "CenterScreen" Height="100" Width="210" ResizeMode="NoResize">
 
<Grid Background="#FFC1C3CB">
<Label Name="Label_Value" Content="Value" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="70"/>
<TextBox Name="TextBox_Value" HorizontalAlignment="Left" Height="23" Margin="90,10,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="100"/>
<Button Name="Button_Random" Content="Random" HorizontalAlignment="Left" Margin="10,41,0,0" VerticalAlignment="Top" Width="70" Height="23"/>
<Button Name="Button_Increment" Content="Increment" HorizontalAlignment="Left" Margin="90,41,0,0" VerticalAlignment="Top" Width="100" Height="23"/>
</Grid>
</Window>
"@
 
$XMLReader = New-Object System.Xml.XmlNodeReader $XML
$XMLForm = [Windows.Markup.XamlReader]::Load($XMLReader)
$buttonIncrement = $XMLForm.FindName('Button_Increment')
$buttonRandom = $XMLForm.FindName('Button_Random')
$textBoxValue = $XMLForm.FindName('TextBox_Value')
 
$buttonRandom.add_click({
$textBoxValue.Text = Get-Random -Minimum 0 -Maximum 10000
})
$buttonIncrement.add_click({++[Int]$textBoxValue.Text})
 
$XMLForm.ShowDialog() | Out-Null</syntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<langsyntaxhighlight Prologlang="prolog">dialog('GUI_Interaction',
[ object :=
GUI_Interaction,
Line 1,895 ⟶ 2,728:
( send(@display, inform, 'Please type a number !'),
send(Input,clear))).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#StringGadget
#Increment
Line 1,925 ⟶ 2,758:
Until Event=#PB_Event_CloseWindow
CloseWindow(0)
EndIf</langsyntaxhighlight>
 
=={{header|Perl 6Python}}==
===Python2 - no classes===
W/out class and using grid layout
{{libheader|Tkinter}}
{{works with|Python|2.7}}
<syntaxhighlight lang="python">
import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()</syntaxhighlight>
 
===Python3 - no classes===
{{libheader|GTK}}
{{libheader|Tkinter}}
{{works with|Python|3.7}}
<syntaxhighlight lang="python">
import random, tkinter.messagebox
from tkinter import *
 
window = Tk()
<lang perl6>use GTK::Simple;
window.geometry("330x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
 
def increase():
my GTK::Simple::App $app .= new(title => 'GUI component interaction');
s.set(int(s.get())+1)
def rand():
if messagebox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
messagebox.showerror('Error', 'Invalid input !')
return "break"
 
e = Entry(text=s)
$app.set_content(
e.grid(column=0, row=0, **options)
my $box = GTK::Simple::VBox.new(
e.bind('<Key>', update)
my $value = GTK::Simple::Entry.new(text => '0'),
my $increment = GTK::Simple::Button.new(label => 'Increment'),
my $random = GTK::Simple::Button.new(label => 'Random'),
)
);
 
b1 = Button(text="Increase", command=increase, **options )
$app.size_request(400, 100);
b1.grid(column=1, row=0, **options)
$app.border_width = 20;
b2 = Button(text="Random", command=rand, **options)
$box.spacing = 10;
b2.grid(column=2, row=0, **options)
 
mainloop()</syntaxhighlight>
$value.changed.tap: {
($value.text ||= '0') ~~ s:g/<-[0..9]>//;
}
 
===Python2 - With classes===
$increment.clicked.tap: {
$value.text += 1;
}
 
$random.clicked.tap: {
# Dirty hack to work around the fact that GTK::Simple doesn't provide
# access to GTK message dialogs yet :P
if run «zenity --question --text "Reset to random value?"» {
$value.text = (^100).pick;
}
}
 
$app.run;</lang>
 
=={{header|Python}}==
{{libheader|Tkinter}}
<langsyntaxhighlight lang="python">import random
from Tkinter import *
import tkMessageBox
 
 
class Application(Frame):
Line 2,012 ⟶ 2,871:
self.random_button = Button(self, text='Random', command=self.random)
self.random_button.pack(**options)
 
 
if __name__ == '__main__':
Line 2,021 ⟶ 2,879:
app.mainloop()
except KeyboardInterrupt:
root.destroy()</langsyntaxhighlight>
 
[[File:GuiInterationPythonGUI_component_interaction_Python.png]]
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
Line 2,057 ⟶ 2,915:
svalue(e) <- sample(1:1000, 1)
})
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket/gui
Line 2,086 ⟶ 2,944:
 
(send frame show #t)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
{{libheader|GTK}}
 
<syntaxhighlight lang="raku" line>use GTK::Simple;
use GTK::Simple::App;
 
my GTK::Simple::App $app .= new(title => 'GUI component interaction');
 
$app.set-content(
my $box = GTK::Simple::VBox.new(
my $value = GTK::Simple::Entry.new(text => '0'),
my $increment = GTK::Simple::Button.new(label => 'Increment'),
my $random = GTK::Simple::Button.new(label => 'Random'),
)
);
 
$app.size-request(400, 100);
$app.border-width = 20;
$box.spacing = 10;
 
$value.changed.tap: {
($value.text ||= '0') ~~ s:g/<-[0..9]>//;
}
 
$increment.clicked.tap: {
my $val = $value.text; $val += 1; $value.text = $val.Str
}
 
$random.clicked.tap: {
# Dirty hack to work around the fact that GTK::Simple doesn't provide
# access to GTK message dialogs yet :P
if run «zenity --question --text "Reset to random value?"» {
$value.text = (^100).pick.Str
}
}
 
$app.run;</syntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
Load "guilib.ring"
 
MyApp = New qApp {
num = 0
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
 
btn1 = new qpushbutton(win1) {
setGeometry(200,200,100,30)
settext("Random")
setclickevent("Rand()")}
 
btn2 = new qpushbutton(win1) {
setGeometry(50,200,100,30)
settext("Increment")
setclickevent("Increment()")}
 
lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)}
show()}
exec()}
 
func Rand
num = string(random(10000))
lineedit1.settext(num)
 
func Increment
lineedit1{ num = text()}
num = string(number(num)+1)
lineedit1.settext(num)
</syntaxhighlight>
 
Output:
 
[[File:CalmoSoftRandom.jpg]]
 
=={{header|Ruby}}==
{{libheader|Shoes}}
<langsyntaxhighlight lang="ruby">Shoes.app(title: "GUI component interaction") do
stack do
textbox = edit_line
Line 2,108 ⟶ 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,153 ⟶ 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,201 ⟶ 3,175:
centerOnScreen()
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|top input vh incButton rndButton|
 
vh := ValueHolder with:0.
Line 2,222 ⟶ 3,196:
rndButton action:[ vh value: Random nextInteger ].
 
top open</langsyntaxhighlight>
{{Out}}
[[File:Guiintsmalltalkx.png]]
Line 2,228 ⟶ 3,202:
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
###--- Our data Model! ---###
Line 2,262 ⟶ 3,236:
set field [expr {int(rand() * 5000)}]
}
}</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gtk+-3.0}}
 
<syntaxhighlight lang="vala">bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
if(!ret){
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
"Invalid value");
dialog.run();
dialog.destroy();
}
return ret;
}
 
 
int main (string[] args) {
Gtk.init (ref args);
 
var window = new Gtk.Window();
window.title = "Rosetta Code";
window.window_position = Gtk.WindowPosition.CENTER;
window.destroy.connect(Gtk.main_quit);
window.set_default_size(0,0);
 
 
var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1);
box.set_border_width(1);
 
 
var label = new Gtk.Label ("Value:");
 
 
var entry = new Gtk.Entry();
entry.set_text("0"); //initialize to zero
entry.activate.connect (() => {
// read and validate the entered value
validate_input(window, entry.get_text());
});
 
 
// button to increment
var ib = new Gtk.Button.with_label("increment");
ib.clicked.connect(() => {
// read and validate the entered value
var str = entry.get_text();
if(validate_input(window, str)){
entry.set_text((int.parse(str)+1).to_string());
}
});
 
 
// button to put in a random value if confirmed
var rb = new Gtk.Button.with_label("random");
rb.clicked.connect (() => {
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.QUESTION,
Gtk.ButtonsType.YES_NO,
"set random value");
var answer = dialog.run();
dialog.destroy();
if(answer == Gtk.ResponseType.YES){
entry.set_text(Random.int_range(0,10000).to_string());
}
});
 
 
box.pack_start(label, false, false, 2);
box.pack_start(entry, false, false, 2);
box.pack_start(ib, false, false, 2);
box.pack_start(rb, false, false, 2);
 
window.add(box);
window.show_all();
 
Gtk.main ();
return 0;
}
</syntaxhighlight>
 
=={{header|Visual Basic}}==
Line 2,270 ⟶ 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 2,331 ⟶ 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 2,464 ⟶ 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