GUI component interaction: Difference between revisions

m
imported>Arakov
 
(60 intermediate revisions by 21 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 49 ⟶ 52:
 
(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 54 ⟶ 119:
 
interaction.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;
with Gtk.Main;
Line 211 ⟶ 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 268 ⟶ 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 301 ⟶ 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 310 ⟶ 415:
<pre>file main.c</pre>
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
Line 357 ⟶ 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 382 ⟶ 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 408 ⟶ 513:
void findRandomNumber( ) ;
} ;
#endif</langsyntaxhighlight>
<pre>file interaction.cpp</pre>
<langsyntaxhighlight lang="cpp">#include <QPushButton>
#include <QLineEdit>
#include <QMessageBox>
Line 457 ⟶ 562:
break ;
}
}</langsyntaxhighlight>
<pre>file main.cpp </pre>
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include "interaction.h"
 
Line 467 ⟶ 572:
theWidget.show( ) ;
return app.exec( ) ;
}</langsyntaxhighlight>
 
===C++11===
Line 474 ⟶ 579:
<pre>main.cpp</pre>
 
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
Line 519 ⟶ 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 596 ⟶ 701:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{libheader|LTK}}
<langsyntaxhighlight lang="lisp">
;; Using the LTK library...
 
Line 640 ⟶ 746:
(gui-test)
 
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
 
<syntaxhighlight lang Delphi="delphi">FILE: Unit1.pas</langsyntaxhighlight>
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Unit1;
 
Line 697 ⟶ 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 743 ⟶ 849:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Echolisp}}==
<langsyntaxhighlight lang="scheme">
(require 'interface)
 
Line 787 ⟶ 893:
 
(panel)
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 36.2x :
<langsyntaxhighlight lang="elena">import forms.;
import extensions.;
 
public class MainWindow : SDIDialog
class Window
{
Button btmIncrement;
object form.
Button btmRandom;
object btmIncrement.
Edit txtNumber;
object btmRandom.
object 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, 180, 140);
txtNumber.setRegion(20, 7, 140, 25);
txtNumber.Caption := "0";
btmIncrement.setRegion(20, 35, 140, 25);
btmIncrement.Caption := "Increment";
btmIncrement.onClick := (args){ self.onButtonIncrementClick() };
btmRandom.setRegion(20, 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.nextInt(99999999))
}
}
private changeTextBoxValue(number)
{
txtNumber.Caption := number.toString()
}
}</syntaxhighlight>
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
include GtkEngine.e -- see OpenEuphoria.org
 
constant -- interface
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)
constructor new
add(pan,inp)
[
add(box,{btn1,btn2})
form := SDIDialog new.
pack(pan,-box)
btmIncrement := Button new.
 
btmRandom := Button new.
show_all(win)
txtNumber := Edit new.
main()
form controls;
-----------------------------
append:btmIncrement;
global function Validate() -- warns about invalid entry, does not prevent it;
append:btmRandom;
-----------------------------
append:txtNumber.
if not t_digit(trim_head(get("Input.text"),"- ")) then
return Warn(win,"Validate","This is not a valid number","Try again!")
form
end if
set caption:"Rosseta Code";
return 1
set x:100 y:100;
end function
set width:160 height:120.
 
---------------------------
txtNumber
global function Increment()
set x:7 y:7;
---------------------------
set width:140 height:25;
set("Input.value",get("Input.value")+1)
set caption:"0".
return 1
end function
btmIncrement
 
set x:7 y:35;
------------------------
set width:140 height:25;
global function Random()
set caption:"Increment";
------------------------
set onClick: (:args)
if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then
[ $self $onButtonIncrementClick ].
set("Input.value",rand(1000))
end if
btmRandom
return 1
set x:7 y:65;
end function
set width:140 height:25;
 
set caption:"Random";
</syntaxhighlight>
set onClick(:args)
 
[ $self $onButtonRandomClick ]
=={{header|F_Sharp|F#}}==
]
<syntaxhighlight lang="fsharp">
// GUI component interaction. Nigel Galloway: June 13th., 2020
$onButtonIncrementClick
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")
var number := txtNumber value; toInt.
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")
number := number + 1.
let l=new System.Windows.Forms.Button(Location=new System.Drawing.Point(135,70),Text="Random")
$self $changeTextBoxValue:number.
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"))
$onButtonRandomClick
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()))))
if(messageDialog open caption:"Inf" question:"Really reset to random value?")
System.Windows.Forms.Application.Run(n)
[
</syntaxhighlight>
$self $changeTextBoxValue(randomGenerator eval:99999999)
]
]
$changeTextBoxValue : number
[
txtNumber set caption(number literal).
]
dispatch => form.
}</lang>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
using fwt
using gfx
Line 929 ⟶ 1,085:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#Include "windows.bi"
 
Line 974 ⟶ 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,032 ⟶ 1,247:
End If
 
End</langsyntaxhighlight>
 
=={{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 1,061 ⟶ 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,067 ⟶ 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,175 ⟶ 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,209 ⟶ 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,242 ⟶ 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,248 ⟶ 1,566:
Example use:
 
<syntaxhighlight lang ="j">interact_run''</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,254 ⟶ 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,346 ⟶ 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,376 ⟶ 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,567 ⟶ 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,589 ⟶ 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,607 ⟶ 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,673 ⟶ 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,732 ⟶ 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,761 ⟶ 2,098:
#demo.val nVal
end if
wait</langsyntaxhighlight>
 
=={{header|M2000 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.
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">
<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 1,792 ⟶ 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 1,802 ⟶ 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,842 ⟶ 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,857 ⟶ 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,943 ⟶ 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,988 ⟶ 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,046 ⟶ 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 2,068 ⟶ 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 2,153 ⟶ 2,728:
( send(@display, inform, 'Please type a number !'),
send(Input,clear))).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#StringGadget
#Increment
Line 2,183 ⟶ 2,758:
Until Event=#PB_Event_CloseWindow
CloseWindow(0)
EndIf</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
{{libheader|GTK}}
 
<lang perl6>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;</lang>
 
=={{header|Phix}}==
{{libheader|pGUI}}
<lang Phix>include pGUI.e
 
Ihandle txt, increment, random, hbx, vbx, dlg
 
function action_cb(Ihandle /*ih*/, integer ch)
if not find(ch,"0123456789-") then return IUP_IGNORE end if
return IUP_CONTINUE
end function
 
function increment_cb(Ihandle /*ih*/)
integer v = IupGetInt(txt,"VALUE")+1
IupSetInt(txt,"VALUE",v)
return IUP_CONTINUE
end function
 
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
 
function esc_close(Ihandle /*ih*/, atom c)
return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE)
end function
 
IupOpen()
txt = IupText(Icallback("action_cb"),"EXPAND=YES")
increment = IupButton("increment",Icallback("increment_cb"))
random = IupButton("random",Icallback("random_cb"))
hbx = IupHbox({increment,random},"MARGIN=0x10, GAP=20")
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
dlg = IupDialog(vbx)
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
IupShow(dlg)
IupMainLoop()
IupClose()</lang>
 
=={{header|Python}}==
===Python2 - no classes===
W/out class and using grid layout
{{libheader|Tkinter}}
{{works with|Python|2.7}}
<lang python>
<syntaxhighlight lang="python">
import random, tkMessageBox
from Tkinter import *
Line 2,291 ⟶ 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}}
<syntaxhighlight lang="python">
import random, tkinter.messagebox
from tkinter import *
 
window = Tk()
window.geometry("330x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
 
def increase():
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)
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>
 
===Python2 - With classes===
{{libheader|Tkinter}}
<langsyntaxhighlight lang="python">import random
from Tkinter import *
import tkMessageBox
 
 
class Application(Frame):
Line 2,339 ⟶ 2,871:
self.random_button = Button(self, text='Random', command=self.random)
self.random_button.pack(**options)
 
 
if __name__ == '__main__':
Line 2,348 ⟶ 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,384 ⟶ 2,915:
svalue(e) <- sample(1:1000, 1)
})
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket/gui
Line 2,413 ⟶ 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}}==
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 2,448 ⟶ 3,019:
num = string(number(num)+1)
lineedit1.settext(num)
</syntaxhighlight>
</lang>
 
Output:
Line 2,456 ⟶ 3,027:
=={{header|Ruby}}==
{{libheader|Shoes}}
<langsyntaxhighlight lang="ruby">Shoes.app(title: "GUI component interaction") do
stack do
textbox = edit_line
Line 2,474 ⟶ 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,519 ⟶ 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,567 ⟶ 3,175:
centerOnScreen()
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|top input vh incButton rndButton|
 
vh := ValueHolder with:0.
Line 2,588 ⟶ 3,196:
rndButton action:[ vh value: Random nextInteger ].
 
top open</langsyntaxhighlight>
{{Out}}
[[File:Guiintsmalltalkx.png]]
Line 2,594 ⟶ 3,202:
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
###--- Our data Model! ---###
Line 2,628 ⟶ 3,236:
set field [expr {int(rand() * 5000)}]
}
}</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gtk3Gtk+-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,657 ⟶ 3,265:
window.window_position = Gtk.WindowPosition.CENTER;
window.destroy.connect(Gtk.main_quit);
window.set_default_size(0,0);
 
 
Line 2,671 ⟶ 3,280:
// read and validate the entered value
validate_input(window, entry.get_text());
});
 
 
Line 2,677 ⟶ 3,286:
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)){
Line 2,696 ⟶ 3,305:
dialog.destroy();
if(answer == Gtk.ResponseType.YES){
entry.set_text(Random.int_range(0,10000).to_string());
}
});
Line 2,713 ⟶ 3,322:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
Line 2,721 ⟶ 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,782 ⟶ 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,915 ⟶ 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