Simple windowed application: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(226 intermediate revisions by more than 100 users not shown)
Line 1:
{{task|GUI}}[[Category:Basic language learning]]{{requires|Graphics}} [[Category:Simple]]
{{task|GUI}}[[Category:Basic language learning]]This task asks to create a window with a label that says "There have been no clicks yet" and a button that says "click me". Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
 
;Task:
Create a window that has:
::#   a label that says   "There have been no clicks yet"
::#   a button that says   "click me"
 
 
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
<br><br>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program simpleWin64.s link with X11 library */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/* constantes X11 */
.equ KeyPressed, 2
.equ ButtonPress, 4
.equ ClientMessage, 33
.equ KeyPressMask, 1
.equ ButtonPressMask, 4
.equ ButtonReleaseMask, 8
.equ ExposureMask, 1<<15
.equ StructureNotifyMask, 1<<17
.equ EnterWindowMask, 1<<4
.equ LeaveWindowMask, 1<<5
 
/*******************************************/
/* Structures */
/********************************************/
/* Button structure */
.struct 0
BT_cbdata:
.struct BT_cbdata + 8
BT_adresse:
.struct BT_adresse + 8
BT_GC:
.struct BT_GC + 8
BT_Font:
.struct BT_Font + 8
BT_fin:
/***************************************************/
/* structure XButtonEvent */
.struct 0
XBE_type: //event type
.struct XBE_type + 8
XBE_serial: // No last request processed server */
.struct XBE_serial + 8
XBE_send_event: // true if this came from a SendEvent request */
.struct XBE_send_event + 8
XBE_display: // Display the event was read from
.struct XBE_display + 8
XBE_window: // "event" window it is reported relative to
.struct XBE_window + 8
XBE_root: // root window that the event occurred on
.struct XBE_root + 8
XBE_subwindow: // child window
.struct XBE_subwindow + 8
XBE_time: // milliseconds
.struct XBE_time + 8
XBE_x: // pointer x, y coordinates in event window
.struct XBE_x + 8
XBE_y:
.struct XBE_y + 8
XBE_x_root: // coordinates relative to root
.struct XBE_x_root + 8
XBE_y_root:
.struct XBE_y_root + 8
XBE_state: // key or button mask
.struct XBE_state + 8
XBE_button: // detail
.struct XBE_button + 8
XBE_same_screen: // same screen flag
.struct XBE_same_screen + 8
XBE_fin:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szRetourligne: .asciz "\n"
szMessErreur: .asciz "Server X11 not found.\n"
szMessErrfen: .asciz "Error create X11 window.\n"
szMessErrGC: .asciz "Error create Graphic Context.\n"
szMessErrButton: .asciz "Error create button.\n"
szMessErrButtonGC: .asciz "Error create button Graphic Context.\n"
szMessGoodBye: .asciz "There have been no clicks yet"
 
szTextButton: .asciz "Click me"
szMessResult: .asciz "You clicked me @ times "
 
szLibDW: .asciz "WM_DELETE_WINDOW" // message close window
 
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
qDisplay: .skip 8 // Display address
qDefScreen: .skip 8 // Default screen address
identWin: .skip 8 // window ident
qCounterClic: .skip 8 // counter clic button
sZoneConv: .skip 24
wmDeleteMessage: .skip 16 // ident close message
stEvent: .skip 400 // provisional size
 
stButton: .skip BT_fin
buffer: .skip 500
 
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main // program entry
main:
mov x0,#0 // open server X
bl XOpenDisplay
cmp x0,#0
beq erreur
// Ok return Display address
ldr x1,qAdrqDisplay
str x0,[x1] // store Display address for future use
mov x28,x0 // and in register 28
// load default screen
ldr x2,[x0,#264] // at location 264
ldr x1,qAdrqDefScreen
str x2,[x1] //store default_screen
mov x2,x0
ldr x0,[x2,#232] // screen list
 
//screen areas
ldr x5,[x0,#+88] // white pixel
ldr x3,[x0,#+96] // black pixel
ldr x4,[x0,#+56] // bits par pixel
ldr x1,[x0,#+16] // root windows
// create window x11
mov x0,x28 //display
mov x2,#0 // position X
mov x3,#0 // position Y
mov x4,600 // weight
mov x5,400 // height
mov x6,0 // bordure ???
ldr x7,0 // ?
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq erreurF
ldr x1,qAdridentWin
str x0,[x1] // store window ident for future use
mov x27,x0 // and in register 27
 
// Correction of window closing error
mov x0,x28 // Display address
ldr x1,qAdrszLibDW // atom name address
mov x2,#1 // False create atom if not exist
bl XInternAtom
cmp x0,#0
ble erreurF
ldr x1,qAdrwmDeleteMessage // address message
str x0,[x1]
mov x2,x1 // address atom create
mov x0,x28 // display address
mov x1,x27 // window ident
mov x3,#1 // number of protocoles
bl XSetWMProtocols
cmp x0,#0
ble erreurF
// authorization of seizures
mov x0,x28 // display address
mov x1,x27 // window ident
ldr x2,qFenetreMask // mask
bl XSelectInput
cmp x0,#0
ble 99f
// create Graphic Context
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC // GC address -> x26
cbz x0,erreurF
// create Graphic Context 1
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC1 // GC address -> x25
cbz x0,erreurF
// Display window
mov x1,x27 // ident window
mov x0,x28 // Display address
bl XMapWindow
 
ldr x0,qAdrszMessGoodBye // display text
bl displayText
 
bl createButton // create button on screen
1: // events loop
mov x0,x28 // Display address
ldr x1,qAdrstEvent // events structure address
bl XNextEvent
ldr x0,qAdrstEvent // events structure address
ldr w0,[x0] // type in 4 first bytes
cmp w0,#ClientMessage // message for close window
beq 2f // yes -> end
cmp w0,#ButtonPress // clic mouse button
beq 3f
// other events
b 1b // and loop
2:
ldr x0,qAdrstEvent // events structure address
ldr x1,[x0,56] // location message code
ldr x2,qAdrwmDeleteMessage // equal ?
ldr x2,[x2]
cmp x1,x2
bne 1b // no loop
mov x0,0 // end Ok
b 100f
//TODO: close ??
 
3:
ldr x0,qAdrstEvent // events structure address
bl evtButtonMouse
b 1b
 
erreurF: // error create window
ldr x0,qAdrszMessErrfen
bl affichageMess
mov x0,1
b 100f
erreur: // error no server x11 active
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,1
100: // program standard end
mov x8,EXIT
svc 0
qBlanc: .quad 0xF0F0F0F0
qAdrqDisplay: .quad qDisplay
qAdrqDefScreen: .quad qDefScreen
qAdridentWin: .quad identWin
qAdrstEvent: .quad stEvent
qAdrszMessErrfen: .quad szMessErrfen
qAdrszMessErreur: .quad szMessErreur
qAdrwmDeleteMessage: .quad wmDeleteMessage
qAdrszLibDW: .quad szLibDW
qAdrszMessGoodBye: .quad szMessGoodBye
qFenetreMask: .quad KeyPressMask|ButtonPressMask|StructureNotifyMask|ExposureMask|EnterWindowMask
/******************************************************************/
/* create Graphic Context */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC:
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x26,x0 // save GC
mov x0,x20 // display address
mov x1,x26
ldr x2,qRed // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x26 // return GC
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszMessErrGC: .quad szMessErrGC
qRed: .quad 0xFF0000
qGreen: .quad 0xFF00
qBlue: .quad 0xFF
qBlack: .quad 0x0
/******************************************************************/
/* create Graphic Context 1 */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC1:
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x25,x0 // save GC
mov x0,x20 // display address
mov x1,x25
ldr x2,qBlanc // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x25 // return GC1
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* create button on screen */
/******************************************************************/
createButton:
stp x21,lr,[sp,-16]! // save registers
// create button window
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,80 // X position
mov x3,150 // Y position
mov x4,60 // weight
mov x5,30 // height
mov x6,2 // border
ldr x7,qBlack
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq 99f
ldr x21,qAdrstButton
str x0,[x21,BT_adresse] // save ident button
str xzr,[x21,BT_cbdata] // for next use
 
// autorisation des saisies
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
ldr x2,qButtonMask // mask
bl XSelectInput
// create Graphic Contexte of button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button ident
mov x2,#0
mov x3,#0
bl XCreateGC
cmp x0,#0
beq 98f
str x0,[x21,BT_GC] // store GC
// display button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
bl XMapWindow
ldr x5,qAdrszTextButton // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
ldr x2,[x21,BT_GC] // GC address
mov x3,#8 // position x
mov x4,#15 // position y
bl XDrawString
b 100f
98:
ldr x0,qAdrszMessErrButtonGC
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrButton
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrstButton: .quad stButton
qAdrszTextButton: .quad szTextButton
qAdrszMessErrButtonGC: .quad szMessErrButtonGC
qAdrszMessErrButton: .quad szMessErrButton
qButtonMask: .quad ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ExposureMask|LeaveWindowMask|EnterWindowMask
 
/******************************************************************/
/* display text on screen */
/******************************************************************/
/* x0 contains the address of text */
displayText:
stp x1,lr,[sp,-16]! // save registers
mov x5,x0 // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,x26 // GC address
mov x3,#50 // position x
mov x4,#100 // position y
bl XDrawString
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* events clic mouse button */
/******************************************************************/
/* x0 contains the address of event */
evtButtonMouse:
stp x1,lr,[sp,-16]! // save registers
ldr x10,[x0,XBE_window] // windows of event
ldr x11,qAdrstButton // load button ident
ldr x12,[x11,BT_adresse]
cmp x10,x12 // equal ?
bne 100f // no
bl eraseText // yes erase the text
ldr x10,qAdrqCounterClic // load counter clic
ldr x0,[x10]
add x0,x0,1 // and increment
str x0,[x10]
ldr x1,qAdrsZoneConv // and decimal conversion
bl conversion10
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and insert result at @ character
bl displayText // and display new text
 
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqCounterClic: .quad qCounterClic
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* erase text */
/******************************************************************/
eraseText:
stp x1,lr,[sp,-16]! // save registers
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,x25 // GC1 address
mov x3,20 // position x
mov x4,70 // position y
mov x5,400
mov x6,50
bl XFillRectangle
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|Ada}}==
{{libheader|GTK|GtkAda}}
{{libheader|GtkAda}}
The following solution is based on bindings to GTK+. Ada as a language does not provide standard GUI. Apart from GtkAda, there exist numerous other GUI bindings and libraries: CLAW, AdaGLUT, GWindow, JEWL, win32ada, QtAda etc.
Ada as a language does not provide standard GUI.
<lang ada>
Apart from GtkAda, there exist numerous other GUI bindings and libraries:
with Gdk.Event; use Gdk.Event;
CLAW, AdaGLUT, GWindow, JEWL, win32ada, QtAda etc.
<syntaxhighlight lang="ada">with Gdk.Event; use Gdk.Event;
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
Line 72 ⟶ 532:
 
Gtk.Main.Main;
end Simple_Windowed_Application;</syntaxhighlight>
 
</lang>
=={{header|APL}}==
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="apl">∇ WindowedApplication
 
⍝ define a form with a label and a button
'Frm'⎕WC'Form' 'Clicks' (40 35) (10 15)
'Lbl'Frm.⎕WC'Label' 'There have been no clicks yet.' (10 10)
'Btn'Frm.⎕WC'Button' 'Click Me' (35 35) (25 25) ('Event' 'Select' 'Click')
 
⍝ callback function
Frm.Clicks←0
Frm.Click←{
Clicks+←1
p0←(1+Clicks=1)⊃'have' 'has'
p1←(1+Clicks=1)⊃'clicks' 'click'
Lbl.Value←'There ',p0,' been ',(⍕Clicks),' ',p1,'.'
}
 
∇</syntaxhighlight>
 
{{works with|GNU APL}}
 
[my-application.apl]
<syntaxhighlight lang="apl">#!/usr/local/bin/apl --script --OFF
 
⍝ Some GTK API consts for readability
⍝ event poll type for X ← ⎕gtk
Blocking ← 1
Nonblocking ← 2
 
∇Z←get_NAME_and_POSITION;GUI_path;CSS_path;Handle
GUI_path ← '/home/me/GNUAPL/workspaces/my-application.glade'
CSS_path ← '/home/me/GNUAPL/workspaces/my-application.css'
Handle ← CSS_path ⎕GTK GUI_path
 
⍝H_ID ← Handle, 'entry1' ⍝ Position field
⍝'<enter name>' ⎕gtk[H_ID] "set_text" ⍝ pre-fill entry
 
⊣⎕gtk Blocking ⍝ Wait for click event
 
Z ← ⊂1↓⎕gtk[Handle, 'entry1'] "get_text"
Z ← Z,⊂1↓⎕gtk[Handle, 'entry2'] "get_text"
⊣Handle ⎕gtk 0
 
⍝ Launch GUI application
get_NAME_and_POSITION
</syntaxhighlight>
 
[my-application.css]
<syntaxhighlight lang="css">/* general button */
.BUTTON { color: #F00; background: #4F4; }
 
/* the OK button */
#OK-button { color: #A22; background: #FFF; }
</syntaxhighlight>
 
[my-application.glade]
<syntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<child>
<placeholder/>
</child>
<child>
<object class="GtkGrid" id="grid1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="row_homogeneous">True</property>
<child>
<object class="GtkLabel" id="label1">
<property name="name">lblEmployee</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Employee</property>
<property name="wrap">True</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label2">
<property name="name">lblPosition</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Position</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">2</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="entry1">
<property name="name">entryEmployee</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="valign">center</property>
</object>
<packing>
<property name="left_attach">3</property>
<property name="top_attach">1</property>
<property name="width">6</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="entry2">
<property name="name">entryPosition</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="valign">center</property>
</object>
<packing>
<property name="left_attach">3</property>
<property name="top_attach">2</property>
<property name="width">6</property>
</packing>
</child>
<child>
<object class="GtkButton" id="btnOK">
<property name="label" translatable="yes">button</property>
<property name="name">OK-button</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="clicked" swapped="no"/>
<style>
<class name="BUTTON"/>
</style>
</object>
<packing>
<property name="left_attach">4</property>
<property name="top_attach">4</property>
<property name="width">2</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
</syntaxhighlight>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
set counter to 0
 
set dialogReply to display dialog ¬
"There have been no clicks yet" buttons {"Click Me", "Quit"} ¬
with title "Simple Window Application"
set theAnswer to button returned of the result
if theAnswer is "Quit" then quit
 
repeat
set counter to counter + 1
set dialogReply to display dialog counter buttons {"Click Me", "Quit"} ¬
with title "Simple Window Application"
set theAnswer to button returned of the result
if theAnswer is "Quit" then exit repeat
end repeat
</syntaxhighlight>
 
===Description===
AppleScript is the MacOS system automation language which creates scripts in various forms, including double-clickable applications, scripted folder actions, inner and inter application control and services, and more.
[https://www.melellington.com/simplewindow/Applescript-SWA.jpg Applescript Output]
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">; Create simple windowed application
<lang Autohotkey>Gui, Add, Text, vGuiText, There have been no clicks yet ; add a Text-Control
Gui, Add, ButtonText, gClickButton xmvTextCtl, clickThere have been no clicks meyet ; add a ButtonText-Control
Gui, Add, Button, gButtonClick xm, click me ; add a Button-Control
Gui, Show ; show the Window
Gui, Show, , Simple windowed application ; show the Window
return ; end of the autoexection section
Return ; end of the auto-execute section
 
ButtonClick: ; the subroutine executed each time the Button-Control is clicked
count++ ; increment the click-counting var
GuiControl, , TextCtl, %count% ; update the Text-Control with the click-counting var
Return ; end of the subroutine
 
ClickButton: ; the subroutine executed each time the Button-Control is clicked
count ++ ; increment the click-counting var
GuiControl, , GuiText , %count% ; update the Text-Control with the click-counting var
return ; end of the subroutine
; exit process when window is closed
GuiClose: ; the subroutine executed when the Window is closed
ExitApp ; exit this process</lang>
Return</syntaxhighlight>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ###
Local $GUI = GUICreate("Clicks", 280, 50, (@DesktopWidth - 280) / 2, (@DesktopHeight - 50) / 2)
Local $lblClicks = GUICtrlCreateLabel("There have been no clicks yet", 0, 0, 278, 20, $SS_CENTER)
Local $btnClicks = GUICtrlCreateButton("CLICK ME", 104, 25, 75, 25)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
 
Local $counter = 0
 
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case $GUI_EVENT_CLOSE
Exit
 
Case $btnClicks
$counter += 1
GUICtrlSetData($lblClicks, "Times clicked: " & $counter)
EndSwitch
WEnd
</syntaxhighlight>
 
=={{header|B4J}}==
<syntaxhighlight lang="freebasic">
#Region Project Attributes
#MainFormWidth: 593
#MainFormHeight: 179
#End Region
 
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private btnClickMe As Button
Private lblClickCounter As Label
Private nClicks As Int = 0
Private aPlurals() As Object = Array As Object(Array As String("has","click"),Array As String("have","clicks"))
End Sub
 
Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
MainForm.Show
End Sub
 
Sub btnClickMe_Action
nClicks = nClicks + 1
Dim aPlural() As Object = aPlurals(IIF(nClicks=1,0,1))
lblClickCounter.Text = "There " & aPlural(0) & " been " & (nClicks) & " " & aPlural(1) & " so far."
End Sub
 
Sub IIF(test As Boolean, trueVal As Object, falseVal As Object) As Object
If test Then
Return trueVal
Else
Return falseVal
End If
End Sub</syntaxhighlight>
 
Layout1.fxml (as B4J uses JavaFX's Scene Builder)
<syntaxhighlight lang="cfm">
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.web.*?>
 
 
<AnchorPane id="paneMain" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="179.0" prefWidth="593.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Button id="btnClickMe" layoutX="254.0" layoutY="90.0" mnemonicParsing="false" text="Click Me">
<font>
<Font size="20.0" />
</font>
</Button>
<Label id="lblClickCounter" layoutX="162.0" layoutY="31.0" text="There have been no clicks as yet.">
<font>
<Font size="20.0" />
</font>
</Label>
</children>
</AnchorPane>
</syntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
Requires BaCon version 4.0.1 or higher, using GTK3.
<syntaxhighlight lang="bacon">OPTION GUI TRUE
PRAGMA GUI gtk3
 
gui = GUIDEFINE(" \
{ type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \
{ type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
{ type=LABEL name=label parent=box height-request=50 label=\"There have been no clicks yet\" } \
{ type=BUTTON name=button parent=box callback=clicked label=\"Click Me\" }")
 
WHILE TRUE
SELECT GUIEVENT$(gui)
CASE "window"
BREAK
CASE "button"
INCR clicked
CALL GUISET(gui, "label", "label", "Button clicks: " & STR$(clicked))
ENDSELECT
WEND</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
window% = FN_newdialog("Rosetta Code", 100, 100, 120, 52, 8, 1000)
PROC_static(window%, "There have been no clicks yet", 100, 10, 10, 100, 14, 0)
PROC_pushbutton(window%, "Click me", FN_setproc(PROCclick), 40, 30, 40, 16, 0)
PROC_showdialog(window%)
REPEAT
WAIT 1
UNTIL !window% = 0
QUIT
DEF PROCclick
PRIVATE clicks%
clicks% += 1
SYS "SetDlgItemText", !window%, 100, "Number of clicks = " + STR$(clicks%)
ENDPROC</syntaxhighlight>
 
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program simple title:'Simple windowed application' // written by CodingFiend
 
var g : record // global tracked mutable state
label : str
nclicks : num
 
========================
calc main_init // our one time initialization for the program
g.label = "There have been no clicks yet"
g.nclicks = 0
 
========================
// In beads you subdivide the screen by slicing it horizontally or vertically
// so as to gradually break it down into pieces, some of which are drawn
horz slice main_draw // our main drawing function
under
draw_rect(fill:DARK_SLATE_GRAY) // fill entire screen
 
// slice the screen into 3 horz pieces, leaving 200 pt for our body
skip 10 al
add 200 pt main_draw2
skip 10 al
 
vert slice main_draw2 // now take the middle horz slice, and slice it vertically
skip 10 al
add 50 pt draw_click_count
skip 2 al
add 80 px draw_button
skip 10 al
 
========================
draw draw_click_count
draw_str(g.label, size:0.7, color:WHITE)
========================
draw draw_button
draw_rect(fill:ORANGE, corner:20 pt, thick:2 pt, color:BROWN)
draw_str("Click me", size:40, indent:8 pt, color:BLACK)
-------------------
track EV_TAP
// update our click count
inc g.nclicks
g.label = to_str(g.nclicks)</syntaxhighlight>
 
=={{header|C}}==
{{libheader|GTK}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <gtk/gtk.h>
 
Line 111 ⟶ 925:
int main(int argc, char **argv)
{
GtkWindow *win;
GtkButton *button;
GtkLabel *label;
GtkVBox *vbox;
 
gtk_init(&argc, &argv);
win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(win, clickme);
button = (GtkButton*)gtk_button_new_with_label(clickme);
label = (GtkLabel*)gtk_label_new("There have been no clicks yet");
gtk_label_set_single_line_mode(label, TRUE);
vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|2.0+}}
{{libheader|System.Windows.Forms}}
<lang csharp>
using System.Windows.Forms;
 
<syntaxhighlight lang="csharp">using System.Windows.Forms;
namespace RosettaCode.SimpleWindowedApplication
 
class RosettaForm : Form
{
public class RosettaForm:Form()
{
privatevar Label labelclickCount = new Label()0;
private Button button = new Button();
private int clickCount = 0;
 
publicvar RosettaFormlabel = new Label();
label.Text = "There have been no clicks yet.";
{
label.TextDock = "There have been no clicks yetDockStyle."Top;
labelControls.AutoSize = trueAdd(label);
button.Text = "Click me.";
button.Dock = DockStyle.Bottom;
button.AutoSize = true;
button.Click += delegate
{
clickCount++;
label.Text = "Clicks so far: " + clickCount;
};
 
var button = new Controls.AddButton(label);
button.Text = "Click Controls.Add(button)Me";
}button.Dock = DockStyle.Bottom;
button.Click += delegate
{
clickCount++;
label.Text = "Number of clicks: " + clickCount + ".";
};
Controls.Add(button);
}
 
classstatic Programvoid Main()
{
staticApplication.Run(new void MainRosettaForm());
{
Application.Run(new RosettaForm());
}
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
{{uses from|Library|Qt|component1=QWidget|component2=QLabel|component3=QPushButton|component4=QVBoxLayout|component5-slots|component6=SIGNAL|component7=SLOT|component8=QApplication}}
{{libheader|Qt}} 4.4 with source files as shown , built from a Makefile generated by the Qt tool qmake
===clickcounter.h===
<syntaxhighlight lang="cpp">#ifndef CLICKCOUNTER_H
#define CLICKCOUNTER_H
 
#include <QWidget>
class QLabel ;
class QPushButton ;
class QVBoxLayout ;
 
class Counter : public QWidget {
Q_OBJECT
public :
Counter( QWidget * parent = 0 ) ;
private :
int number ;
QLabel *countLabel ;
QPushButton *clicker ;
QVBoxLayout *myLayout ;
private slots :
void countClicks( ) ;
} ;
#endif</syntaxhighlight>
===clickcounter.cpp===
<syntaxhighlight lang="cpp">#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include "clickcounter.h"
 
Counter::Counter( QWidget * parent ) : QWidget( parent ) {
number = 0 ;
countLabel = new QLabel( "There have been no clicks yet!" ) ;
clicker = new QPushButton( "click me" ) ;
connect ( clicker , SIGNAL( clicked( ) ) , this , SLOT( countClicks( ) ) ) ;
myLayout = new QVBoxLayout ;
myLayout->addWidget( countLabel ) ;
myLayout->addWidget( clicker ) ;
setLayout( myLayout ) ;
}
 
void Counter::countClicks( ) {
number++ ;
countLabel->setText( QString( "The button has been clicked %1 times!").arg( number ) ) ;
}</syntaxhighlight>
===main.cpp===
<syntaxhighlight lang="cpp">#include <QApplication>
#include "clickcounter.h"
 
int main( int argc , char *argv[ ] ) {
QApplication app( argc , argv ) ;
Counter counter ;
counter.show( ) ;
return app.exec( ) ;
}</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(ns counter-window
(:import (javax.swing JFrame JLabel JButton)))
 
(defmacro on-action [component event & body]
`(. ~component addActionListener
(proxy [java.awt.event.ActionListener] []
(actionPerformed [~event] ~@body))))
 
(defn counter-app []
(let [counter (atom 0)
label (JLabel. "There have been no clicks yet")
button (doto (JButton. "Click me!")
(on-action evnt
(.setText label
(str "Counter: " (swap! counter inc)))))
panel (doto (JPanel.)
(.setOpaque true)
(.add label)
(.add button))]
(doto (JFrame. "Counter App")
(.setContentPane panel)
(.setSize 300 100)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))))
</syntaxhighlight>
 
=={{header|Common Lisp}}==
Line 181 ⟶ 1,070:
{{works with|McCLIM}}
 
<langsyntaxhighlight lang="lisp">(defpackage #:rcswa
(:use #:clim #:clim-lisp))
(in-package #:rcswa)</langsyntaxhighlight>
 
This version uses CLIM's command system:
 
<langsyntaxhighlight lang="lisp">(define-application-frame simple-windowed-application ()
((clicks :initform 0
:accessor clicks-of))
Line 205 ⟶ 1,094:
(define-simple-windowed-application-command (com-click-me :menu t)
()
(incf (clicks-of *application-frame*)))</langsyntaxhighlight>
 
This version uses an explicit pushbutton gadget, and may be used if more direct control over the UI layout and behavior is needed:
 
<langsyntaxhighlight lang="lisp">(define-application-frame simple-windowed-application ()
((clicks :initform 0
:accessor clicks-of))
Line 235 ⟶ 1,124:
(vertically (:equalize-width nil :align-x :center)
the-label
(spacing (:thickness 10) the-button)))))</langsyntaxhighlight>
 
In either case, the window is opened with:
 
<langsyntaxhighlight lang="lisp">(run-frame-top-level (make-application-frame 'simple-windowed-application))</langsyntaxhighlight>
 
=={{header|D}}==
Line 245 ⟶ 1,134:
{{works with|D|1}}
{{libheader|DFL}}
<langsyntaxhighlight lang="d">module winapp ;
import dfl.all ;
import std.string ;
Line 275 ⟶ 1,164:
void main() {
Application.run(new MainForm);
}</langsyntaxhighlight>
 
===Hybrid===
Line 297 ⟶ 1,186:
}
SimpleWindow.d:
<langsyntaxhighlight lang="d">module SimpleWindow;
import tango.text.convert.Integer;
import tango.core.Thread; // For Thread.yield
Line 332 ⟶ 1,221:
Thread.yield();
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 342 ⟶ 1,231:
'''NOTE:''' The project name here must match the name of the file.
 
<syntaxhighlight lang="delphi">-- begin file --
<lang delphi>
-- begin file --
 
Program SingleWinApp ;
Line 429 ⟶ 1,317:
Application.Run ;
 
end. // Program </syntaxhighlight>
</lang>
 
=={{header|E}}==
{{libheader|Swing}}
{{works with|E-on-Java}}
<syntaxhighlight lang="e">when (currentVat.morphInto("awt")) -> {
var clicks := 0
def w := <swing:makeJFrame>("Rosetta Code 'Simple Windowed Application'")
w.setContentPane(JPanel`
${def l := <swing:makeJLabel>("There have been no clicks yet.")} $\
${def b := <swing:makeJButton>("Click Me")}
`)
b.addActionListener(def _ {
to actionPerformed(_) {
clicks += 1
l.setText(`Number of clicks: $clicks`)
}
})
w.pack()
w.show()
}</syntaxhighlight>
}
 
=={{header|EchoLisp}}==
UI elements are HTML DOM Nodes. '''ui-add''' adds an element to the UI. '''ui-on-event''' adds a (Lisp) event handler to an element.
<syntaxhighlight lang="scheme">
(define (ui-add-button text) ;; helper
(define b (ui-create-element "button" '((type "button"))))
(ui-set-html b text)
(ui-add b))
(define (panel )
(ui-clear)
(define *clicks* 0)
(define text (ui-create-element "span" '((style "font-weight:bold"))))
(ui-add text)
(ui-set-html text "No click yet")
 
(define btn (ui-add-button "Click-me"))
(define (count-clicks elem)
(++ *clicks*)
(ui-set-html text *clicks*))
(ui-on-click btn count-clicks)
 
(stdout-hide #t)
(stdin-hide #t)) ;; end panel definition
 
(panel)
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x:
<syntaxhighlight lang="elena">import forms;
import extensions;
 
public class MainWindow : SDIDialog
{
Label lblClicks;
Button btmClickMe;
//Store how much clicks the user doed
int clicksCount;
constructor new()
<= super new()
{
lblClicks := Label.new();
btmClickMe := Button.new();
clicksCount := 0;
self
.appendControl(lblClicks)
.appendControl(btmClickMe);
self.Caption := "Rosseta Code";
self.setRegion(100, 100, 160, 80);
lblClicks.Caption := "Clicks: 0";
lblClicks.setRegion(10, 2, 160, 20);
 
btmClickMe.Caption := "Click me";
btmClickMe.setRegion(7, 20, 140, 30);
btmClickMe.onClick := (args){ self.onButtonClick(); };
}
private onButtonClick()
{
clicksCount := clicksCount + 1;
lblClicks.Caption := "Clicks: " + clicksCount.toString();
}
}</syntaxhighlight>
 
=={{header|Euphoria}}==
===EuWinGUI===
{{libheader|EuWinGUI}}
<syntaxhighlight lang="euphoria">include EuWinGUI.ew
 
Window("EuWinGUI - Simple windowed application",100,100,360,100)
constant Button1 = Control(Button,"Click me",250,20,80,25)
constant Label1 = Control(Label,"There have been no clicks yet",10,25,200,18)
 
integer clicks
clicks = 0
 
-- Event loop
while 1 do
WaitEvent()
if EventOwner = Button1 and Event = Click then
clicks += 1
SetText(Label1,sprintf("You clicked me %d times",clicks))
end if
end while
 
CloseApp(0)</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<syntaxhighlight lang="fsharp">open System.Windows.Forms
 
let mutable clickCount = 0
 
let form = new Form()
 
let label = new Label(Text = "There have been no clicks yet.", Dock = DockStyle.Top)
form.Controls.Add(label)
 
let button = new Button(Text = "Click me", Dock = DockStyle.Bottom)
button.Click.Add(fun _ ->
clickCount <- clickCount+1
label.Text <- sprintf "Number of clicks: %i." clickCount)
form.Controls.Add(button)
 
Application.Run(form)</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: accessors arrays kernel math math.parser namespaces
sequences ui ui.gadgets ui.gadgets.borders ui.gadgets.buttons
ui.gadgets.grids ui.gadgets.labels ui.gadgets.worlds ;
IN: rosetta-code.simple-windowed-application
 
SYMBOL: n
 
CONSTANT: on-btn-press [
parents second n get number>string <label> { 0 1 }
grid-add drop n inc
]
 
: build-ui ( -- ) [
f
T{ world-attributes { title "Simple windowed application" } }
clone
"click me" on-btn-press <border-button> 1array
"There have been no clicks yet" <label> 1array
2array <grid>
{ 100 100 } <border>
>>gadgets
open-window
] with-ui ;
 
: main ( -- ) 1 n set build-ui ;
 
MAIN: main</syntaxhighlight>
 
=={{header|Fantom}}==
 
<syntaxhighlight lang="fantom">
using fwt
using gfx
 
class SimpleApplication
{
public static Void main ()
{
Window
{
title = "Simple Window Application"
size = Size(350, 50)
clicked := 0
label := Label
{
text = "There have been no clicks yet"
}
Button
{
text = "Click me"
onAction.add |Event e|
{
clicked += 1
label.text = "There have been $clicked clicks"
}
},
label,
}.open
}
}
</syntaxhighlight>
 
=={{header|Forth}}==
===with MINOS===
{{works with|bigFORTH}}
{{libheader|MINOS}}
<syntaxhighlight lang="forth">also minos
text-label ptr click-label
Variable click# click# off
: click-win ( -- ) screen self window new window with
X" There have been no clicks yet" text-label new
dup F bind click-label
^ S[ 1 click# +!
click# @ 0 <# #S s" Number of clicks: " holds #>
click-label assign ]S X" Click me" button new
&2 vabox new panel s" Clicks" assign show endwith ;
click-win</syntaxhighlight>
 
===The same with Theseus===
{{works with|bigFORTH}}
{{libheader|Theseus}}
<syntaxhighlight lang="forth">#! xbigforth
\ automatic generated code
\ do not edit
 
also editor also minos also forth
 
component class ccount
public:
early widget
early open
early dialog
early open-app
text-label ptr click#
( [varstart] ) cell var clicks ( [varend] )
how:
: open new DF[ 0 ]DF s" Click counter" open-component ;
: dialog new DF[ 0 ]DF s" Click counter" open-dialog ;
: open-app new DF[ 0 ]DF s" Click counter" open-application ;
class;
 
ccount implements
( [methodstart] ) ( [methodend] )
: widget ( [dumpstart] )
X" There have been no clicks yet" text-label new ^^bind click#
^^ S[ 1 clicks +!
clicks @ 0 <# #S s" Number of clicks: " holds #> click# assign ]S ( MINOS ) X" Click me" button new
&2 vabox new panel
( [dumpend] ) ;
: init ^>^^ assign widget 1 :: init ;
class;
 
: main
ccount open-app
$1 0 ?DO stop LOOP bye ;
script? [IF] main [THEN]
previous previous previous</syntaxhighlight>
 
 
===with Tk/wish===
{{works with|gforth|0.7.3}}
{{libheader|Tk}}
Creates a GUI with 'wish' from tk library. Uses pipes on standard input and output (created throw linux system calls).
 
<syntaxhighlight lang="forth">0 value tk-in
0 value tk-out
variable #clicks
0 #clicks !
 
: wish{ \ send command to wish
tk-in to outfile-id ;
: }wish \ finish command to wish
tk-in flush-file throw
stdout to outfile-id ;
 
 
: add-one 1 #clicks +! ;
: update-wish wish{ .\" .label configure -text \"clicks: " #clicks @ . .\" \"" cr }wish ;
 
: counting
begin
tk-out key-file
dup '+' = if add-one update-wish then \ add one if '+' received
4 = until ; \ until Ctrl-D, wish exit
 
: initiating
s" mkfifo tk-in tk-out" system
s" wish <tk-in >tk-out &" system
s" tk-in" w/o open-file throw to tk-in
s" tk-out" r/o open-file throw to tk-out
wish{ .\" pack [ label .label -text \"There have been no clicks yet\" ] " cr }wish
wish{ .\" pack [ button .click -text \"Click Me\" -command { puts \"+\" } ] " cr }wish ;
 
: cleaning
tk-in close-file
tk-out close-file
s" rm tk-in tk-out" system ;
 
initiating counting cleaning</syntaxhighlight>
 
===with iMops===
{{works with|iMops|2.23}}
Macintosh only - Uses native MacOS GUI calls to Cocoa.
<syntaxhighlight lang="forth">
:class TextView' super{ TextView }
:m put: ( addr len -- )
0 #ofChars: self SetSelect: self
insert: self ;m
;class
 
Window+ w
View wview
Button b
100 30 100 20 setFrame: b
TextView' t
200 30 200 15 setFrame: t
 
\ the running count is always on the stack
\ so a variable for that is not needed
:noname
1+ \ increment the count
" Number of clicks: " put: t
dup deciNumstr insert: t ; setAction: b \ update the text representation of count
 
: go
b addview: wview
t addview: wview
300 30 430 230 put: frameRect
frameRect " Test" docWindow
wview new: w show: w
" click me" setTitle: b
" There have been no clicks yet" put: t
0 ; \ the number of clicks start at zero
 
go</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#Include "windows.bi"
 
Dim As HWND Window_Main, Static_Text, Button_Click
Dim As MSG msg
Dim As Integer Num_Click
Dim As String Text
 
'Create a window with a static text control and a button:
Window_Main = CreateWindow("#32770", "Simple Windowed Application", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)
Static_Text = CreateWindow("STATIC", "There have been no clicks yet", WS_VISIBLE Or WS_CHILD Or WS_BORDER, 10, 30, 300, 20, Window_Main, 0, 0, 0)
Button_Click = CreateWindow("BUTTON", "Click me", WS_VISIBLE Or WS_CHILD, 100, 70, 100, 20, Window_Main, 0, 0, 0)
'Windows message loop:
Num_Click = 0
While GetMessage(@msg, Window_Main, 0, 0)
TranslateMessage(@msg)
DispatchMessage(@msg)
Select Case msg.hwnd
Case Button_Click
If msg.message = WM_LBUTTONDOWN Then
Num_Click = Num_Click + 1
If Num_Click = 1 Then
Text = "Button has been clicked once"
Else
Text = "Button has been clicked " + Str(Num_Click) + " times"
End If
SetWindowText(Static_Text, Text)
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
_label
_clickMeBtn
end enum
 
void local fn BuildWindow
window _window, @"Simple Windowed Application", (0,0,366,59)
 
textlabel _label, @"There have been no clicks yet", (18,23,250,16)
 
button _clickMeBtn,,, @"Click Me", (267,13,86,32)
end fn
 
void local fn ButtonClicked
static long clickCount = 0
 
clickCount++
textlabel _label, fn StringWithFormat( @"The button has been clicked %ld times", clickCount )
end fn
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _clickMeBtn : fn ButtonClicked
end select
end select
end fn
 
fn BuildWindow
 
on dialog fn DoDialog
 
HandleEvents</syntaxhighlight>
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">iCount As Integer 'Counter of clicks!
hLabel As Label 'We need a Label
 
Public Sub Form_Open()
Dim hButton As Button 'We need a Button
 
With Me 'Set the Form's Properties..
.height = 75 'Set the Height
.Width = 300 'Set the Width
.Arrangement = Arrange.Vertical 'Arrange items vertically
.Padding = 5 'Border area
.Title = "Click counter!" 'Title displayed on the Form
End With
 
hlabel = New Label(Me) 'Add a Label to the form
 
With hlabel 'Set the Label's Properties..
.expand = True 'Expand the Label to fit the Form
.Text = "There have been no clicks yet" 'Add Text to the Label
.Alignment = Align.Center 'Center the Text
End With
 
hButton = New Button(Me) As "Button1" 'Add a Button to the form as Event "Button1"
 
With hButton 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Click me" 'Add Text (The '&' adds a keyboard shortcut)
End With
 
End
 
Public Sub Button1_Click() 'When the Button is clicked..
 
Inc iCount 'Increase the value of iCount
hLabel.text = "The button has been clicked " & iCount & " times" 'Display the amount of clicks"
 
End</syntaxhighlight>
 
=={{header|Gastona}}==
<syntaxhighlight lang="gastona">#javaj#
 
<frames> main, Simple click counter
<layout of main>
PANEL, X
bClick me, lClicks
#data#
 
<NN> 0
<lClicks> //There have been no clicks yet
#listix#
 
<-- bClick me>
NUM=, NN, NN+1
-->, lClicks data!,, //@<NN> clicks so far
 
</syntaxhighlight>
 
=={{header|Go}}==
{{libheader|go-gtk}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"github.com/mattn/go-gtk/gtk"
)
 
func main() {
gtk.Init(nil)
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.SetTitle("Click me")
label := gtk.NewLabel("There have been no clicks yet")
var clicks int
button := gtk.NewButtonWithLabel("click me")
button.Clicked(func() {
clicks++
if clicks == 1 {
label.SetLabel("Button clicked 1 time")
} else {
label.SetLabel(fmt.Sprintf("Button clicked %d times",
clicks))
}
})
vbox := gtk.NewVBox(false, 1)
vbox.Add(label)
vbox.Add(button)
window.Add(vbox)
window.Connect("destroy", func() {
gtk.MainQuit()
})
window.ShowAll()
gtk.Main()
}</syntaxhighlight>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">import groovy.swing.SwingBuilder
 
def countLabel, count = 0, swing = new SwingBuilder()
count = 0
def frame = swing.frame(title:'Click frame') {
new SwingBuilder().edt {
flowLayout()
frame(title:'Click frame', pack: true, show: true) {
countLabel = label(text:"There have been no clicks yet." )
vbox {
button(text:'Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."})
countLabel = label("There have been no clicks yet.")
}
button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."})
frame.pack()
}
frame.show()
}
=={{header|IDL}}==
}</syntaxhighlight>
pro counter, ev
 
widget_control, ev.top, get_uvalue=tst
'''with binding:'''
tst[1] = tst[1]+1
<syntaxhighlight lang="groovy">import groovy.swing.SwingBuilder
widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)')
import groovy.beans.Bindable
widget_control, ev.top, set_uvalue=tst
 
end
@Bindable class Model {
Integer count = 0
}
model = new Model()
new SwingBuilder().edt {
frame(title:'Click frame', pack: true, show: true) {
vbox {
label(text: bind(source: model, sourceProperty: 'count',
converter: { v -> !v ? "There have been no clicks yet." : "Clicked ${v} time(s)."}))
button('Click Me', actionPerformed: {model.count++})
}
}
}</syntaxhighlight>
 
=={{header|Guish}}==
<syntaxhighlight>
c=0
p=|p|;v
l=|l|;<"There have been no clicks yet"o
b=|b|;=>c{
c = add(1, @c)
@l<@c
}<"click me"
@p<<<@b<<<@l
@l w
@p,o+
</syntaxhighlight>
 
=={{header|Haskell}}==
{{libheader|Gtk}} from [http://hackage.haskell.org/packages/hackage.html HackageDB]
<syntaxhighlight lang="haskell">import Graphics.UI.Gtk
import Data.IORef
 
main :: IO ()
main = do
initGUI
window <- windowNew
window `onDestroy` mainQuit
windowSetTitle window "Simple Windowed App"
set window [ containerBorderWidth := 10 ]
 
hbox <- hBoxNew True 5
 
set window [ containerChild := hbox ]
lab <- labelNew (Just "There have been no clicks yet")
id = widget_base(title = 'Window Title',column=1)
button <- buttonNewWithLabel "Click me"
ld = widget_label(id, value = 'There have been no clicks yet.')
set hbox [ containerChild := lab ]
widget_control, /realize, id, set_uvalue=[ld,0]
set hbox [ containerChild := button ]
dummy = widget_button(id,value=' Click Me ',event_pro='counter')
xmanager, "Simple", Id
m <- newIORef 0
end
=={{header|J}}==
 
onClicked button $ do
SIMPLEAPP=: 0 : 0
v <- readIORef m
pc simpleApp;
writeIORef m (v+1)
xywh 136 8 44 12;cc inc button;cn "Click me";
set lab [ labelText := "There have been " ++ show (v+1) ++ " clicks" ]
xywh 136 23 44 12;cc cancel button;cn "Cancel";
 
xywh 7 10 115 11;cc shownText static;cn "There have been no clicks yet.";
widgetShowAll window
pas 6 6;pcenter;
 
rem form end;
mainGUI</syntaxhighlight>
)
 
=={{header|HicEst}}==
<syntaxhighlight lang="hicest"> CHARACTER label="There have been no clicks yet"
 
DO count = 1, 1E100 ! "forever"
DLG(Button="Click me", Width=3, TItle=label) ! Width=3 to display full length label
label = "Clicked " // count // "time(s)"
ENDDO
 
END</syntaxhighlight>
 
==Icon and {{header|Unicon}}==
 
This version is Unicon-specific:
<syntaxhighlight lang="unicon">import gui
$include "guih.icn"
 
procedure main()
SimpleWindow().show_modal()
end
 
class SimpleWindow : Dialog(label, button, count)
method component_setup()
self.set_attribs("size=222,139")
label := Label()
label.set_pos("24", "24")
label.set_internal_alignment("l")
label.set_label("There have been no clicks yet.")
self.add(label)
button := TextButton()
button.set_pos(24, 53)
button.set_label("click me")
button.set_internal_alignment("c")
button.connect(self, "incr", ACTION_EVENT)
self.add(button)
end
 
method incr()
/count := 0
label.set_label("There have been "||(count+:=1)||" clicks.")
end
 
initially
self.Dialog.initially()
end</syntaxhighlight>
 
=={{header|IDL}}==
<syntaxhighlight lang="idl">pro counter, ev
widget_control, ev.top, get_uvalue=tst
tst[1] = tst[1]+1
widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)')
widget_control, ev.top, set_uvalue=tst
end
id = widget_base(title = 'Window Title',column=1)
simpleApp_run=: 3 : 0
ld = widget_label(id, value = 'There have been no clicks yet.')
wd SIMPLEAPP
widget_control, /realize, id, set_uvalue=[ld,0]
simpleApp_accum=: 0 NB. initialize accumulator
dummy = widget_button(id,value=' Click Me ',event_pro='counter')
wd 'pshow;'
xmanager, "Simple", Id
)
end</syntaxhighlight>
simpleApp_close=: 3 : 0
 
wd'pclose'
=={{header|J}}==
)
'''J 9.x''' (note: the J 8.x version works fine under J 9.x)<syntaxhighlight lang="j">simple_run=: {{
simple_clicks=: 0 NB. initialize accumulator
wd {{)n
pc simple closeok escclose;
cc click button;cn "Click me";
cc message static;cn "There have been no clicks yet.";
pshow;
}}}}
simple_run''
simple_click_button=: {{wd 'set message text Button-use count: ',": simple_clicks=: 1+simple_clicks}}</syntaxhighlight>
simpleApp_cancel_button=: 3 : 0
'''J 8.x'''
simpleApp_close<nowiki>''</nowiki>
<syntaxhighlight lang="j">SIMPLEAPP=: noun define
)
pc simpleApp;
cc inc button;cn "Click me";
simpleApp_inc_button=: 3 : 0
cc shownText static;cn "There have been no clicks yet.";
wd 'set shownText *','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum
)
 
simpleApp_run<nowiki>''</nowiki>=: verb define
wd SIMPLEAPP
simpleApp_accum=: 0 NB. initialize accumulator
wd 'pshow;'
)
 
simpleApp_inc_button=: verb define
wd 'set shownText text ','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum
)
 
simpleApp_close=: wd bind 'pclose'
simpleApp_cancel=: simpleApp_close
 
simpleApp_run''</syntaxhighlight>
 
'''J 6.x'''
<syntaxhighlight lang="j">SIMPLEAPP=: noun define
pc simpleApp;
xywh 131 11 44 12;cc inc button;cn "Click me";
xywh 7 10 115 11;cc shownText static;cn "There have been no clicks yet.";
pas 6 6;pcenter;
rem form end;
)
 
simpleApp_run=: verb define
wd SIMPLEAPP
simpleApp_accum=: 0 NB. initialize accumulator
wd 'pshow;'
)
 
simpleApp_inc_button=: verb define
wd 'set shownText *','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum
)
 
simpleApp_close=: wd bind 'pclose'
simpleApp_cancel=: simpleApp_close
 
simpleApp_run''</syntaxhighlight>
 
=={{header|Java}}==
{{libheader|AWT}}
{{libheader|Swing}}
<langsyntaxhighlight lang="java">import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Line 570 ⟶ 2,029:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Clicks extends JFrame implements ActionListener{
public class Clicks extends JFrame{
private long clicks = 0;
private JLabel label;
private JButton clicker;
private String text;
 
public Clicks(){
super("Clicks");//set window title
text = "There have been no clicks yet";
JLabel label = new JLabel(text"There have been no clicks yet");
JButton clicker = new JButton("click me");
clicker.addActionListener(this);//listen to the button
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
label.setText("There have been " + (++clicks) + " clicks");//change the text
}
}
);
setLayout(new BorderLayout());//handles placement of components
add(label,BorderLayout.CENTER);//add the label to the biggest section
add(clicker,BorderLayout.SOUTH);//put the button underneath it
label.setPreferredSize(new Dimension(300,100));//nice big label
setSize(300,200);//stretch out the window
label.setHorizontalAlignment(JLabel.CENTER);//text not up against the side
pack();//fix layout
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X"
setVisible(true);//show it
}
public static void main(String[] args){
SwingUtilities.invokeLater( //Swing UI updates should not happen on the main thread
new Clicks();//call the constructor where all the magic happens
() -> new Clicks() //call the constructor where all the magic happens
);
}
}</syntaxhighlight>
public void actionPerformed(ActionEvent arg0) {
 
if(arg0.getSource() == clicker){//if they clicked the button
=={{header|JavaFX Script}}==
text = "There have been " + (++clicks) + " clicks";
{{libheader|JavaFX 1.2}}
label.setText(text);//change the text
<syntaxhighlight lang="javafx">import javafx.stage.*;
}
import javafx.scene.*;
import javafx.scene.layout.*;
}
import javafx.scene.control.*;
}</lang>
 
Stage {
scene: Scene {
width: 300 height: 200
content: VBox {
var clicks: Integer;
 
spacing: 10
content: [
Label {
def varText = bind if (clicks == 0) then "no clicks yet" else "{clicks} clicks"
text : bind "There have been {varText}"
}
Button {
text: "click me"
onMouseClicked: function(e) { clicks++; }
}
]
}
}
}</syntaxhighlight>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
<html>
<head>
<title>Simple Window Application</title>
</head>
 
<body>
<br> &nbsp &nbsp &nbsp &nbsp
 
<script type="text/javascript">
var box = document.createElement('input')
box.style.position = 'absolute'; // position it
box.style.left = '10px';
box.style.top = '60px';
document.body.appendChild(box).style.border="3px solid white";
document.body.appendChild(box).value = "There have been no clicks yet";
document.body.appendChild(box).style['width'] = '220px';
var clicks = 0;
function count_clicks() {
document.body.appendChild(box).remove()
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
 
<button type="button" onclick="count_clicks()"> Click me</button>
<pre><p> Clicks: <a id="clicks">0</a> </p></pre>
</body>
 
</html>
</syntaxhighlight>
 
[http://melellington.com/simplewindow/javascript-simple-window.html Javascript Output]
 
----
 
=={{header|Julia}}==
Uses the Gtk library.
<syntaxhighlight lang="julia">using Gtk.ShortNames
 
function clickwindow()
clicks = 0
win = Window("Click Counter", 300, 100) |> (Frame() |> (vbox = Box(:v)))
lab = Label("There have been no clicks yet.")
but = Button("click me")
push!(vbox, lab)
push!(vbox, but)
set_gtk_property!(vbox, :expand, lab, true)
set_gtk_property!(vbox, :spacing, 20)
callback(w) = (clicks += 1; set_gtk_property!(lab, :label, "There have been $clicks button clicks."))
id = signal_connect(callback, but, :clicked)
Gtk.showall(win)
c = Condition()
endit(w) = notify(c)
signal_connect(endit, win, :destroy)
wait(c)
end
 
clickwindow()
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.0.6
 
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*
 
class Clicks : JFrame(), ActionListener {
private var clicks = 0
private val label: JLabel
private val clicker: JButton
private var text: String
 
init {
text = "There have been no clicks yet"
label = JLabel(text)
clicker = JButton("click me")
clicker.addActionListener(this) // listen to the button
layout = BorderLayout() // handles placement of components
add(label, BorderLayout.CENTER) // add the label to the biggest section
add(clicker, BorderLayout.SOUTH) // put the button underneath it
setSize(300, 200) // stretch out the window
defaultCloseOperation = EXIT_ON_CLOSE // stop the program on "X"
isVisible = true // show it
}
 
override fun actionPerformed(arg0: ActionEvent) {
if (arg0.source == clicker) { // if they clicked the button
if (clicks == 0) text = "There has been " + (++clicks) + " click"
else text = "There have been " + (++clicks) + " clicks"
label.text = text // change the text
}
}
}
 
fun main(args: Array<String>) {
Clicks() // call the constructor where all the magic happens
}</syntaxhighlight>
 
{{libheader|TornadoFX}}
<syntaxhighlight lang="scala">
import tornadofx.*
 
class ClicksView: View("Clicks example") {
var clicks = 0
override val root = vbox(5) {
var label1 = label("There have been no clicks yet")
button("Click me!") { action { label1.text = "Clicked ${++clicks} times." } }
}
}
 
class ClicksApp: App(ClicksView::class)
 
fun main(args: Array<String>) = launch<ClicksApp>(args)
</syntaxhighlight>
 
=={{header|Lambdatalk}}==
The environment is a small wiki: http://epsilonwiki.free.fr/lambdaway/
 
The code is tested in this page: http://epsilonwiki.free.fr/lambdaway/?view=popup
<syntaxhighlight lang="scheme">
1) the label: {div {@ id="label"} There have been no clicks yet }
2) the button: {input {@ type="button" value="click me" onclick="CLICKAPP.inc()" }}
3) the script: {script °° code °°} where code is a single function:
 
var CLICKAPP = (function() {
var counter = 0;
var inc = function() {
counter++;
getId('label').innerHTML =
'There are ' + counter + ' clicks now';
};
return {inc:inc}
})();
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">nomainwin
button #demo.btn, "Click Me", [btnClick], UL, 20, 50
statictext #demo.num, "There have been no clicks yet.", 20, 100, 240, 30
open "Rosetta Task: Simple windowed application" for window as #demo
#demo "trapclose [quit]"
nClicks = 0
wait
 
[quit]
close #demo
end
 
[btnClick]
nClicks = nClicks + 1
#demo.num "The button has been clicked ";nClicks;" times."
wait</syntaxhighlight>
 
=={{header|Lingo}}==
The standard approach in Lingo for creating GUIs and assigning scripts for handling user interaction is to use the graphical IDE/GUI-Builder "Director". But windows and sprites (visual elements) can also be created and scripted programmatically only:
<syntaxhighlight lang="lingo">on startMovie
 
-- window settings
_movie.stage.title = "Hello World!"
_movie.stage.titlebarOptions.visible = TRUE
_movie.stage.rect = rect(0,0,320, 240)
_movie.centerStage = 1
 
-- create a label (called "field" in Director)
m = new(#field)
m.name = "label"
m.rect = rect(0,0,320,0)
m.text = "There have been no clicks yet"
m.alignment = "center"
-- create sprite, assign field
_movie.puppetSprite(1, TRUE)
sprite(1).member = m
sprite(1).loc = point(0,80)
-- create a button
m = new(#button)
m.rect = rect(0,0,220,0)
m.text = "click me"
m.alignment = "center"
-- create sprite, assign button
_movie.puppetSprite(2, TRUE)
sprite(2).member = m
sprite(2).loc = point(50,105)
-- create new script at runtime, assign it to button sprite
m = new(#script)
m.scriptType = #score
m.scriptText = "on mouseDown"&RETURN&\
" m=member("&QUOTE&"label"&QUOTE&")"&RETURN&\
" m.text=string(integer(m.text)+1)"&RETURN&\
"end"
sprite(2).scriptInstanceList.add(m.script.new())
 
-- force immediate update
_movie.updateStage()
-- show the window
_movie.stage.visible = 1
 
end</syntaxhighlight>
 
 
=={{header|LiveCode}}==
 
The LiveCode script here meets the specification 100%,
but is not in common LiveCode style. Typically the
mouseUp command would be attached to the button
rather than to the 'card' (window). Nevertheless, the card
is in the object's message path so the button works well.
 
<syntaxhighlight lang="livecode">global count
on openCard
put empty into count
put "There have been no clicks yet" into field "clicks"
end openCard
on mouseUp
add 1 to count
put count into field "clicks"
end mouseUp</syntaxhighlight>
 
[http://melellington.com/simplewindow/livecode-simple-window.jpg LiveCode Output]
 
 
 
----
 
=={{header|Logo}}==
 
{{works with|MSWlogo}}
 
<syntaxhighlight lang="logo">to clickwindow
windowCreate "root "clickWin [Click that button!!!] 0 0 100 100 []
Make "i 0
staticCreate "clickWin "clickSt [There have been no clicks yet] 0 0 100 20
buttonCreate "clickWin "clickBtn [click me] 10 20 80 20 ~
[Make "i :i+1 ~
ifelse :i=1 [staticUpdate "clickSt (list "clicked :i "time)] ~
[staticUpdate "clickSt (list "clicked :i "times)]]
end</syntaxhighlight>
 
The window is opened with:
<syntaxhighlight lang="logo">clickwindow</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">require"iuplua"
l = iup.label{title="There have been no clicks yet."}
b = iup.button{title="Click me!"}
clicks = 0
function b:button_cb()
clicks = clicks + 1
l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct.
end
dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"}
dlg:show()
 
if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
iup.MainLoop()
end</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
For labels M2000 window manager use Buttons with locked property to true. We can press enter because when the form open, default control is the Button1 (the second button we make). edit
 
For label1 we make a linked property, named Caption$ (we can use dot, so we can use label1.caption$). See that we make as second linked property for the same property but with a number (cap). How this is possible?
 
Μ2000 controls are internal COM objects and as those they can use Variant type properties and these properties can convert as they need. So if need a string and we pass a number then the number change to string.
 
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Declare Form1 Form
Declare Label1 Button Form Form1
Declare Button1 Button Form Form1
Method Label1,"move", 2000, 2000, 4000, 600
Method Button1,"move", 2000, 3000, 4000, 600
With Label1, "Caption" as caption$, "Locked", true, "Caption" as cap
With Button1, "Caption", "click me", "Default", True ' make this the default control
caption$="There have been no clicks yet"
m=0
Function Button1.Click {
m++
cap=m
}
Method Form1, "Show",1
Declare Form1 Nothing
}
Checkit
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">DynamicModule[{n = 0},
CreateDialog[{Dynamic@
TextCell@If[n == 0, "There have been no clicks yet", n],
Button["click me", n++]}]]</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">rollout buttonClick "Button Click"
(
label l "There have been no clicks yet"
button clickMe "Click me"
local clickCount = 0
 
on clickMe pressed do
(
clickCount += 1
l.text = ("Number of clicks: " + clickCount as string)
)
)
createDialog buttonClick</syntaxhighlight>
 
=={{header|Modula-3}}==
{{libheader|Trestle}}
 
This code uses <tt>Trestle</tt>, a windowing toolkit developed for Modula-3.
<syntaxhighlight lang="modula3">MODULE Click EXPORTS Main;
 
IMPORT Fmt, TextVBT, ButtonVBT, VBT, Axis, HVSplit, TrestleComm, Trestle;
 
VAR label := TextVBT.New("There have been no clicks yet.");
button := ButtonVBT.New(TextVBT.New("Click me!"), Clicked);
main := HVSplit.Cons(Axis.T.Ver, label, button, adjustable := FALSE);
count := 0;
 
PROCEDURE Clicked(<*UNUSED*>button: ButtonVBT.T; <*UNUSED*>READONLY cd: VBT.MouseRec) =
BEGIN
INC(count);
TextVBT.Put(label, "Button pressed: " & Fmt.Int(count));
END Clicked;
 
<*FATAL TrestleComm.Failure*>
BEGIN
Trestle.Install(main);
Trestle.AwaitDelete(main);
END Click.</syntaxhighlight>
 
To compile the above code, you need to create a file called <tt>m3makefile</tt> which contains:
<pre>
import("ui")
import("libm3")
implementation("Click")
program("Click")
</pre>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">import Nanoquery.Util.Windows
 
// define the necessary objects
$w = new("Window")
$b = new("Button")
$l = new("Label")
 
$b.setParent($w)
$l.setParent($w)
 
// define the amount of clicks
$clicks = 0
 
// a function to update the label
def updateLabel($caller, $event)
global $clicks
global $l
 
$clicks = $clicks+1
$l.setText(str($clicks))
 
global $clicks = $clicks
end
 
// prepare the components to be displayed
$w.setSize(200,200)
$b.setText("click me")
$b.setPosition(0,100)
$l.setText("There have been no clicks yet")
 
// set the button's event handler to the function updateLabel
$b.setHandler($updateLabel)
 
// show the window
$w.show()</syntaxhighlight>
 
=={{header|Nim}}==
{{libheader|GTK2}}
<syntaxhighlight lang="nim">import gtk2
 
nim_init()
 
var
win = windowNew WINDOW_TOPLEVEL
button = buttonNew "Click me"
label = labelNew "There have been no clicks yet"
vbox = vboxNew(true, 1)
counter = 0
 
proc clickedMe(o: var PButton, l: PLabel) =
inc counter
l.setText "You clicked me " & $counter & " times"
 
win.setTitle "Click me"
vbox.add label
vbox.add button
win.add vbox
discard win.signal_connect("delete-event", SignalFunc mainQuit, nil)
discard button.signal_connect("clicked", SignalFunc clickedMe, label)
win.showAll()
main()</syntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|GNUstep}}
<langsyntaxhighlight lang="objc">#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
 
@interface ClickMe : NSWindow
{
NSButton *button_button;
NSTextField *text_text;
int counter_counter;
}
- (void)applicationDidFinishLaunching: (NSNotification *)notification;
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;
- (void)advanceCounter: (id)sender;
@end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="objc">@implementation ClickMe : NSWindow
-(idinstancetype) init
{
NSButton *button = [[NSButton alloc] init];
NSRect buttonRect;
int totalWindowHeight;
 
counter = 0;
button = [[NSButton alloc] init];
[button setButtonType: NSToggleButton];
[button setTitle: @"Click Me"];
Line 644 ⟶ 2,526:
[button setTarget: self];
[button setAction: @selector(advanceCounter:)];
NSRect buttonRect = [button frame];
 
NSTextField *text = [[NSTextField alloc]
initWithFrame: NSMakeRect(buttonRect.origin.x, buttonRect.size.height,
buttonRect.size.width, buttonRect.size.height)];
Line 658 ⟶ 2,540:
setFrameSize: NSMakeSize( [text frame].size.width, buttonRect.size.height ) ];
 
int totalWindowHeight = buttonRect.size.height + [text frame].size.height;
 
if ((self = [super initWithContentRect: NSMakeRect(100, 100,
[self
initWithContentRect: NSMakeRect(100, 100,
[text frame].size.width, totalWindowHeight)
styleMask: (NSTitledWindowMask | NSClosableWindowMask)
backing: NSBackingStoreBuffered
defer: NO];)) {
_counter = 0;
_button = button;
_text = text;
 
[[self contentView] addSubview: text]; [text release_text];
[[self contentView] addSubview: button]; [button release_button];
 
[self setTitle: @"Click Me!"];
[self center];
 
[self setTitle: @"Click Me!"];
[self center];
}
return self;
}
 
 
-(void) dealloc
{
[button release];
[text release];
[super dealloc];
}
 
- (void)applicationDidFinishLaunching: (NSNotification *)notification
Line 696 ⟶ 2,573:
- (void)advanceCounter: (id)sender
{
[_text setStringValue: [NSString stringWithFormat: @"Clicked %d times", ++_counter]];
counter++;
[text setStringValue: [NSString stringWithFormat: @"Clicked %d times", counter]];
}
@end
Line 704 ⟶ 2,580:
int main()
{
@autoreleasepool {
ClickMe *clickme;
NSApplication *app = [NSApplication sharedApplication];
NSAutoreleasePool *pool;
ClickMe *clickme = [[ClickMe alloc] init];
NSApplication *app;
[app setDelegate: clickme];
 
[app run];
pool = [[NSAutoreleasePool alloc] init];
}
app = [NSApplication sharedApplication];
clickme = [[ClickMe alloc] init];
[app setDelegate: clickme];
[app run];
[clickme release];
[pool release];
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
* with '''Labltk''', the '''Tk''' ocamlOCaml binding:
<langsyntaxhighlight lang="ocaml">#directory "+labltk"
#load "labltk.cma"
 
Line 735 ⟶ 2,606:
Tk.pack [Tk.coe label; Tk.coe b];
Tk.mainLoop ();
;;</langsyntaxhighlight>
 
* with '''LablGTK2''', the '''GTK2''' OCaml binding:
<syntaxhighlight lang="ocaml">open GMain
 
let window = GWindow.window ~border_width:2 ()
let vbox = GPack.vbox ~packing:window#add ()
let label = GMisc.label ~text:"There have been no clicks yet" ~packing:vbox#pack ()
let button = GButton.button ~label:"click me" ~packing:vbox#pack ()
 
let () =
window#event#connect#delete ~callback:(fun _ -> true);
window#connect#destroy ~callback:Main.quit;
button#connect#clicked ~callback:window#destroy;
window#show ();
Main.main ()</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">/* REXX ***************************************************************************************
* 18.06.2014 Walter Pachl shortened from Rony Flatscher's bsf4oorexx (see sourceforge) samples
* Look there for ShowCount.rxj
* bsf4oorexx lets the ooRexx program use Java classes
**********************************************************************************************/
userData=.directory~new -- a directory which will be passed to Rexx with the event
 
-- create a framed Java window, set a title text
win=.bsf~new("java.awt.Frame", "Show Count")
-- Create a Java RexxProxy for controlling the closing of the application
rexxCloseEH =.RexxCloseAppEventHandler~new -- Rexx event handler
-- Create Java RexxProxy for the Rexx event handler
rpCloseEH=BsfCreateRexxProxy(rexxCloseEH,,"java.awt.event.WindowListener" )
win~addWindowListener(rpCloseEH) -- add RexxProxy event handler
 
-- create a Java push button
but=.bsf~new("java.awt.Button","Press me!")
-- Create a RexxProxy for the button Rexx event handler
rp=BsfCreateRexxProxy(.RexxShowCountEventHandler~new,userData,"java.awt.event.ActionListener")
but~addActionListener(rp) -- add RexxProxy event handler
 
lab=.bsf~new("java.awt.Label") -- create a Java label,set it to show the text centered
userData~label=lab -- save label object for later use in event handler
lab~setAlignment(lab~center) -- set alignment to center
lab~setText("Button was not yet pressed") -- assign initial text to the label
 
win ~~add("Center",lab) ~~add("South",but) -- add the label and the button to the frame
win ~~pack -- now calculate all widget dimensions
call enlargeWidth win,but,120 -- enlarge the width of the frame and the button
 
win ~~setVisible(.true) ~~toFront -- make frame visible and move it to the front
 
userData~i=0 -- set counter to 0
 
rexxCloseEH~waitForExit -- wait until we are allowed to end the program
 
-- if Java was loaded by Rexx,then terminate Java's RexxEngine to inhibit callbacks from Java
call BSF.terminateRexxEngine
 
::requires BSF.CLS -- get Java support
 
/* enlarge the width of the frame and of the button without using a layout manager */
::routine enlargeWidth
use arg win,but,addToWidth
winDim=win~getSize -- get frame's dimension
winDim~width+=addToWidth -- increase width
win~setSize(winDim) -- set frame's dimension
 
/* ------------------------------------------------------------------------ */
/* Rexx event handler to set "close app" indicator */
::class RexxCloseAppEventHandler
::method init -- constructor
expose closeApp
closeApp = .false -- if set to .true, then it is safe to close the app
 
::attribute closeApp -- indicates whether app should be closed
 
::method unknown -- intercept unhandled events,do nothing
 
::method windowClosing -- event method (from WindowListener)
expose closeApp
closeApp=.true -- indicate that the app should close
 
::method waitForExit -- method blocks until attribute is set to .true
expose closeApp
guard on when closeApp=.true
 
/* ------------------------------------------------------------------------ */
/* Rexx event handler to process tab changes */
::class RexxShowCountEventHandler
::method actionPerformed
use arg eventObject,slotDir
call showCount slotDir~userData
 
/* ------------------------------------------------------------------------ */
::routine ShowCount -- increment counter and show text
use arg userData
userData~i+=1 -- increment counter in directory object
Select -- construct text part
When userData~i=1 Then how_often='once'
When userData~i=2 Then how_often='twice'
When userData~i=3 Then how_often='three times'
Otherwise how_often=userData~i 'times'
End
userData~label~setText("Button was pressed" how_often) -- display text</syntaxhighlight>
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">functor
import
Application
QTk at 'x-oz://system/wp/QTk.ozf'
define
Count = {NewCell 0}
Label
GUI = td(action:proc {$} {Application.exit 0} end %% exit on close
label(text:"There have been no clicks yet." handle:Label)
button(text:"Click Me"
action:proc {$}
Count := @Count + 1
{Label set(text:"Number of clicks: "#@Count#".")}
end
))
Window = {QTk.build GUI}
{Window show}
end
</syntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{libheader|SysUtils}}
{{libheader|glib2}}
{{libheader|Gtk2}}
Ported from the C example.
<syntaxhighlight lang="pascal">Program SimpleWindowApplication;
 
uses
SysUtils,
glib2,
Gtk2;
 
const
clickme = 'Click Me';
MAXLEN = 64;
 
var
counter: integer = 0;
 
procedure clickedme(o: PGtkButton; d: pointer); cdecl;
var
nt: Pchar;
l: PGtkLabel;
begin
l := Gtk_LABEL(d);
inc(counter);
nt := Pchar('You clicked me ' + inttostr(counter) + ' times');
Gtk_label_set_text(l, nt);
end;
 
var
win: PGtkWindow;
button: PGtkButton;
Mylabel: PGtkLabel;
vbox: PGtkVBox;
 
begin
Gtk_init(@argc, @argv);
win := PGtkWindow(Gtk_window_new(Gtk_WINDOW_TOPLEVEL));
Gtk_window_set_title(win, clickme);
button := PGtkButton(Gtk_button_new_with_label(clickme));
Mylabel := PGtkLabel(Gtk_label_new('There have been no clicks yet'));
Gtk_label_set_single_line_mode(Mylabel, TRUE);
vbox := PGtkVBox(Gtk_vbox_new(TRUE, 1));
Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(Mylabel));
Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(button));
Gtk_container_add(Gtk_CONTAINER(win), Gtk_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), 'delete-event', TGCallBack(@Gtk_main_quit), NULL);
g_signal_connect(G_OBJECT(button), 'clicked', TGCallBack(@clickedme), Mylabel);
Gtk_widget_show_all(Gtk_WIDGET(win));
Gtk_main();
end.</syntaxhighlight>
 
=={{header|Perl}}==
==={{libheader|Perl/Tk}}===
<syntaxhighlight lang ="perl"> use Tk;
$main = MainWindow->new;
$l = $main->Label('-text' => 'There have been no clicks yet.')->pack;
$count = 0;
$main->Button(
-text => ' Click Me ',
-command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); },
)->pack;
MainLoop();</lang>
 
$main = MainWindow->new;
{{libheader|GTK}}
$l = $main->Label('-text' => 'There have been no clicks yet.')->pack;
<lang perl> use Gtk '-init';
$count = 0;
$main->Button(
-text => ' Click Me ',
-command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); },
)->pack;
MainLoop();</syntaxhighlight>
 
==={{libheader|GTK}} {{works with|Perl/Gtk}}===
<syntaxhighlight lang="perl">use Gtk '-init';
 
# Window.
$window = Gtk::Window->new;
$window->signal_connect('destroy' => sub { Gtk->main_quit; });
 
# VBox.
$vbox = Gtk::VBox->new(0, 0);
$window->add($vbox);
 
# Label.
$label = Gtk::Label->new('There have been no clicks yet.');
$vbox->add($label);
 
# Button.
$count = 0;
$button = Gtk::Button->new(' Click Me ');
$vbox->add($button);
$button->signal_connect('clicked', sub {
$label->set_text(++$count);
});
 
# Show.
$window->show_all;
 
# Main loop.
Gtk->main;</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/simplewindow.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Simple_window.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">btn</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">vbox</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">clicks</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">click_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*btn*/</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">clicks</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"clicked %d times"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">clicks</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span><span style="color: #0000FF;">;</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;">lbl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"There have been no clicks yet"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">btn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Click me"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"click_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">vbox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lbl</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupFill</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">btn</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupFill</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;">vbox</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"MARGIN=10x10, GAP=10, RASTERSIZE=400x0"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Simple windowed application"</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>-->
The above is cross platform, win/lnx, 32/64 bit, and runs in a browser.
An older win32-only version can be found [[Simple_windowed_application/Arwen|here]].
 
=={{header|PicoLisp}}==
The standard PicoLisp GUI is HTTP based. Connect your browser to
http://localhost:8080 after starting the following script.
<syntaxhighlight lang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
 
(zero *Count)
 
(de start ()
(app)
(action
(html 0 "Clicks" NIL NIL
(form NIL
(gui '(+Init +TextField) "There have been no clicks yet")
(----)
(gui '(+JS +Button) "click me"
'(set> (field -1)
(pack "Clicked " (inc '*Count) " times") ) ) ) ) ) )
 
(server 8080 "!start")
(wait)</syntaxhighlight>
 
=={{header|Pike}}==
{{libheader|Gtk2}}
<syntaxhighlight lang="pike">GTK2.Widget mainwindow,clickcnt,clicker;
int clicks;
 
void click()
{
clickcnt->set_text("Clicks: "+(++clicks));
}
 
int main()
{
GTK2.setup_gtk();
mainwindow=GTK2.Window(GTK2.WindowToplevel);
mainwindow->set_title("Click counter");
mainwindow->add(GTK2.Vbox(0,10)
->add(clickcnt=GTK2.Label("There have been no clicks yet"))
->add(clicker=GTK2.Button("Click me"))
)->show_all();
mainwindow->signal_connect("delete_event",lambda() {exit(0);});
clicker->signal_connect("clicked",click);
return -1;
}
</syntaxhighlight>
 
=={{header|PowerShell}}==
===Windows Forms===
{{works with|PowerShell|3}}
<syntaxhighlight lang="powershell">
$Label1 = [System.Windows.Forms.Label]@{
Text = 'There have been no clicks yet'
Size = '200, 20' }
$Button1 = [System.Windows.Forms.Button]@{
Text = 'Click me'
Location = '0, 20' }
$Button1.Add_Click(
# Window.
{
$window = Gtk::Window->new;
$Script:Clicks++
$window->signal_connect('destroy' => sub { Gtk->main_quit; });
If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
Else { $Label1.Text = "There have been $Clicks clicks" }
} )
$Form1 = New-Object System.Windows.Forms.Form
# VBox.
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )
$vbox = Gtk::VBox->new(0, 0);
$window->add($vbox);
$Clicks = 0
# Label.
$label = Gtk::Label->new('There have been no clicks yet.');
$vbox->add($label);
$Result = $Form1.ShowDialog()
# Button.
</syntaxhighlight>
$count = 0;
{{works with|PowerShell|2}}
$button = Gtk::Button->new(' Click Me ');
<syntaxhighlight lang="powershell">
$vbox->add($button);
Add-Type -AssemblyName System.Windows.Forms
$button->signal_connect('clicked', sub {
$label->set_text(++$count);
$Label1 = New-Object System.Windows.Forms.Label
});
$Label1.Text = 'There have been no clicks yet'
$Label1.Size = '200, 20'
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = 'Click me'
$Button1.Location = '0, 20'
$Button1.Add_Click(
{
$Script:Clicks++
If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
Else { $Label1.Text = "There have been $Clicks clicks" }
} )
$Form1 = New-Object System.Windows.Forms.Form
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )
$Clicks = 0
$Result = $Form1.ShowDialog()
</syntaxhighlight>
===WPF===
<syntaxhighlight lang="powershell">
[xml]$Xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name = "Window1"
Width = "200"
Height = "120"
ShowInTaskbar = "True">
<StackPanel>
<Label
x:Name = "Label1"
Height = "40"
Width = "200"
Content = "There have been no clicks"/>
<Button
x:Name = "Button1"
Height = "25"
Width = "60"
Content = "Click me"/>
</StackPanel>
</Window>
"@
$Window1 = [Windows.Markup.XamlReader]::Load( [System.Xml.XmlNodeReader]$Xaml )
$Label1 = $Window1.FindName( "Label1" )
$Button1 = $Window1.FindName( "Button1" )
$Button1.Add_Click(
{
$Script:Clicks++
If ( $Clicks -eq 1 ) { $Label1.Content = "There has been 1 click" }
Else { $Label1.Content = "There have been $Clicks clicks" }
} )
$Clicks = 0
# Show.
$window->show_all;
$Result = $Window1.ShowDialog()
# Main loop.
</syntaxhighlight>
Gtk->main;</lang>
 
=={{header|Processing}}==
<syntaxhighlight lang="java">
//Aamrun, 11th July 2022
 
int labelLeft = 100, labelTop = 100, labelWidth = 440, labelHeight = 100;
 
int labelTextLeft = 150, labelTextTop = 150;
 
int buttonLeft = 170, buttonTop = 230, buttonWidth = 300, buttonHeight = 100;
 
boolean hasBeenClicked = false;
 
int clicks = 0;
 
 
void setup(){
size(640,480);
fill(255);
rect(labelLeft,labelTop,labelWidth,labelHeight);
fill(0);
textSize(30);
text("There have been no clicks yet",labelTextLeft,labelTextTop);
fill(#c0c0c0);
rect(buttonLeft,buttonTop,buttonWidth,buttonHeight);
fill(0);
text("Click Me !", buttonLeft + 50,buttonTop + 50);
}
 
void mousePressed(){
if(mouseX > buttonLeft && mouseX < buttonLeft + buttonWidth
&& mouseY > buttonTop && mouseY < buttonTop + buttonHeight){
hasBeenClicked = true;
clicks++;
}
}
 
void draw(){
if(hasBeenClicked == true){
fill(255);
rect(labelLeft,labelTop,labelWidth,labelHeight);
fill(0);
textSize(30);
text("Clicks : " + str(clicks),labelTextLeft,labelTextTop);
}
}
 
 
</syntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<syntaxhighlight lang="prolog">:- dynamic click/1.
 
dialog('Simple windowed application',
[ object :=
Simple_windowed_application,
parts :=
[ Simple_windowed_application :=
dialog('Simple windowed application'),
Name :=
label(name, 'There have been no clicks yet'),
BtnClick :=
button(button)
],
modifications :=
[ BtnClick := [ label := 'Click me !'
]
],
layout :=
[ area(Name,
area(40, 20, 200, 18)),
area(BtnClick,
area(90, 60, 80, 24))
],
behaviour :=
[
BtnClick := [message := message(@prolog, btnclick, Name)]
]
]).
 
btnclick(Label) :-
retract(click(V)),
V1 is V+1,
assert(click(V1)),
sformat(A, '~w click(s)', [V1]),
send(Label, selection, A).
 
simple_windowed :-
retractall(click(_)),
assert(click(0)),
make_dialog(D, 'Simple windowed application'),
send(D, open).
 
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Define window_0
Define window_0_Text_0, window_0_Button_1
Define clicks, txt$, flags
flags = #PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_ScreenCentered
window_0 = OpenWindow(#PB_Any, 408, 104, 280, 45, "Simple windowed application", flags)
If window_0
SmartWindowRefresh(window_0, #True)
window_0_Text_0 = TextGadget(#PB_Any, 5, 5, 165, 20, "There have been no clicks yet")
window_0_Button_1 = ButtonGadget(#PB_Any, 190, 10, 85, 30, "Click me")
 
Repeat
Select WaitWindowEvent()
Case #PB_Event_Gadget
Select EventGadget()
Case window_0_Text_0
Case window_0_Button_1
clicks + 1
txt$ = "You Clicked " + Str(clicks) + " time"
If clicks > 1: txt$ + "s": EndIf
SetGadgetText(window_0_Text_0, txt$)
EndSelect
Case #PB_Event_CloseWindow
End
EndSelect
ForEver
EndIf</syntaxhighlight>
 
=={{header|Python}}==
 
==={{libheader|Tkinter}}===
{{works with|Python|3.7}}
<lang python>from Tkinter import Tk, Label, Button
<syntaxhighlight lang="python">from functools import partial
import tkinter as tk
 
def on_click(label: tk.Label,
def update_label():
counter: tk.IntVar) -> None:
global n
ncounter.set(counter.get() += 1)
llabel["text"] = f"Number of clicks: %d{counter.get()}" % n
 
wdef = Tkmain():
window = tk.Tk()
n = 0
window.geometry("200x50+100+100")
l = Label(w, text="There have been no clicks yet")
label = tk.Label(master=window,
l.pack()
text="There have been no clicks yet")
Button(w, text="click me", command=update_label).pack()
label.pack()
w.mainloop()</lang>
counter = tk.IntVar()
===The same in OO manner===
update_counter = partial(on_click,
<lang python>#!/usr/bin/env python
label=label,
from Tkinter import Button, Frame, Label, Pack
counter=counter)
button = tk.Button(master=window,
text="click me",
command=update_counter)
button.pack()
window.mainloop()
 
if __name__ == '__main__':
class ClickCounter(Frame):
def clickmain(self):
</syntaxhighlight>
self.count += 1
 
self.label['text'] = 'Number of clicks: %d' % self.count
The same in OO manner:
<syntaxhighlight lang="python">import tkinter as tk
def createWidgets(self):
 
self.label = Label(self, text='here have been no clicks yet')
class ClickCounter(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
tk.Pack.config(self)
self.label = tk.Label(self, text='There have been no clicks yet')
self.label.pack()
self.button = tk.Button(self, text='click me', command=self.click)
text='click me',
command=self.click)
self.button.pack()
def __init__(self, master=None):
Frame.__init__(self, master)
Pack.config(self)
self.createWidgets()
self.count = 0
if __name__=="__main__":
ClickCounter().mainloop()</lang>
{{libheader|PyQt}}
<lang python>import sys
from qt import *
 
def update_labelclick(self):
self.count += 1
global i
self.label['text'] = f'Number of clicks: {self.count}'
i += 1
lbl.setText("Number of clicks: %i" % i)
 
i = 0
app = QApplication(sys.argv)
win = QWidget()
win.resize(200, 100)
lbl = QLabel("There have been no clicks yet", win)
lbl.setGeometry(0, 15, 200, 25)
btn = QPushButton("click me", win)
btn.setGeometry(50, 50, 100, 25)
btn.connect(btn, SIGNAL("clicked()"), update_label)
win.show()
app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
app.exec_loop()</lang>
 
if __name__ == "__main__":
{{libheader|wxPython}}
ClickCounter().mainloop()
<lang python>import wx
</syntaxhighlight>
 
==={{libheader|PyQt}}===
class MyApp(wx.App):
<syntaxhighlight lang="python">from functools import partial
def click(self, event):
from itertools import self.count += 1
self.label.SetLabel("Count: %d" % self.count)
 
from PyQt5.QtWidgets import (QApplication,
def OnInit(self):
QLabel,
frame = wx.Frame(None, wx.ID_ANY, "Hello from wxPython")
QPushButton,
self.count = 0
QWidget)
self.button = wx.Button(frame, wx.ID_ANY, "Click me!")
from PyQt5.QtCore import QRect
self.label = wx.StaticText(frame, wx.ID_ANY, "Count: 0")
self.Bind(wx.EVT_BUTTON, self.click, self.button)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.button, True, wx.EXPAND)
self.sizer.Add(self.label, True, wx.EXPAND)
frame.SetSizer(self.sizer)
frame.SetAutoLayout(True)
self.sizer.Fit(frame)
frame.Show(True)
self.SetTopWindow(frame)
return True
 
LABEL_GEOMETRY = QRect(0, 15, 200, 25)
app = MyApp(0)
BUTTON_GEOMETRY = QRect(50, 50, 100, 25)
app.MainLoop()</lang>
 
 
def on_click(_, label, counter=count(1)):
label.setText(f"Number of clicks: {next(counter)}")
 
 
def main():
application = QApplication([])
window = QWidget()
label = QLabel(text="There have been no clicks yet",
parent=window)
label.setGeometry(LABEL_GEOMETRY)
button = QPushButton(text="click me",
parent=window)
button.setGeometry(BUTTON_GEOMETRY)
update_counter = partial(on_click,
label=label)
button.clicked.connect(update_counter)
window.show()
application.lastWindowClosed.connect(window.close)
application.exec_()
 
 
if __name__ == '__main__':
main()
</syntaxhighlight>
 
==={{libheader|wxPython}}===
<syntaxhighlight lang="python">import wx
 
 
class ClickCounter(wx.Frame):
def __init__(self):
super().__init__(parent=None)
self.count = 0
self.button = wx.Button(parent=self,
label="Click me!")
self.label = wx.StaticText(parent=self,
label="There have been no clicks yet")
self.Bind(event=wx.EVT_BUTTON,
handler=self.click,
source=self.button)
 
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(window=self.button,
proportion=1,
flag=wx.EXPAND)
self.sizer.Add(window=self.label,
proportion=1,
flag=wx.EXPAND)
self.SetSizer(self.sizer)
self.sizer.Fit(self)
 
def click(self, _):
self.count += 1
self.label.SetLabel(f"Count: {self.count}")
 
 
if __name__ == '__main__':
app = wx.App()
frame = ClickCounter()
frame.Show()
app.MainLoop()
</syntaxhighlight>
 
=={{header|R}}==
{{libheader|gWidgets}}
 
{{libheader|gWidgetstcltk}}
 
gWidgetsRGtk2 or gWidgetsrJava can be used as an alternative to gWidgetstcltk.
<syntaxhighlight lang="r">library(gWidgets)
library(gWidgetstcltk)
win <- gwindow()
lab <- glabel("There have been no clicks yet", container=win)
btn <- gbutton("click me", container=win, handle=function(h, ...)
{
val <- as.numeric(svalue(lab))
svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1))
}
)</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket/gui
 
(define frame (new frame% [label "There have been no clicks yet"]))
 
(define num-clicks 0)
(define (cb obj me)
(set! num-clicks (add1 num-clicks))
(send frame set-label (format "~a" num-clicks)))
 
(new button% [parent frame] [label "Click me"] [callback cb])
(send frame show #t)
</syntaxhighlight>
 
=={{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 => 'Simple Windowed Application');
 
$app.size-request(350, 100);
 
$app.set-content(
GTK::Simple::VBox.new(
my $label = GTK::Simple::Label.new( text => 'There have been no clicks yet'),
my $button = GTK::Simple::Button.new(label => 'click me'),
)
);
 
$app.border-width = 40;
 
$button.clicked.tap: {
state $clicks += 1;
$label.text = "There has been $clicks click{ 's' if $clicks != 1 }";
}
 
$app.run;</syntaxhighlight>
 
=={{header|RapidQ}}==
RapidQ has form designer that produces RapidQ Basic source code. You can get the same result by writing the code yourself with a text editor. Then compile it either from within IDE or by using the command line compiler.
 
<syntaxhighlight lang ="rapidq"> DECLARE SUB buttonClick
 
CREATE form AS QForm
Center
Height = 120
Width = 300
 
CREATE text AS QLabel
Caption = "There have been no clicks yet."
Left = 30: Top = 20
END CREATE
 
CREATE button1 AS QButton
Caption = "Click me"
Left = 100: Top = 50: Height = 25: Width = 100
OnClick = buttonClick
END CREATE
END CREATE
 
SUB buttonClick
STATIC count AS Integer
count = count+1
text.Caption = "Clicked " + STR$(count) + " times."
END SUB
 
form.ShowModal</langsyntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">REBOL [
Title: "Simple Windowed Application"
URL: http://rosettacode.org/wiki/Simple_Windowed_Application
]
 
clicks: 0
 
; Simple GUI's in REBOL can be defined with 'layout', a
; special-purpose language (dialect, in REBOL-speak) for specifying
; interfaces. In the example below, I describe a gradient background
; with a text label and a button. The block in the button section
; details what should happen when it's clicked on -- increment the
; number of clicks and update the label text.
 
; The 'view' function paints the layout on the screen and listens for
; events.
 
view layout [
backdrop effect [gradient 0x1 black coal]
 
label: vtext "There have been no clicks yet."
 
button maroon "click me" [
clicks: clicks + 1
set-face label reform ["clicks:" clicks]
]
]</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red []
 
clicks: 0
 
view [
t: text "There have been no clicks yet" return
button "click me" [
clicks: clicks + 1
t/data: rejoin ["clicks: " clicks]
]
]</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(150,200,100,30)
settext("click me")
setclickevent("clickme()")}
 
Lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)}
show()}
Exec()}
 
func clickme
num += 1
lineedit1.settext( "you clicked me " + num + " times")
</syntaxhighlight>
Output:
 
[[File:CalmoSoftWindow.jpg]]
 
=={{header|Ruby}}==
{{libheader|Ruby/Tk}}
<langsyntaxhighlight lang="ruby">require 'tk'
str = TkVariable.new("no clicks yet")
count = 0
Line 912 ⟶ 3,430:
pack
end
Tk.mainloop</langsyntaxhighlight>
 
{{libheader|Shoes}}
<syntaxhighlight lang="ruby">Shoes.app do
stack do
@count = 0
@label = para "no clicks yet"
button "click me" do
@count += 1
@label.text = "click: #@count"
end
end
end</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">msg$ = "There have been no clicks yet"
[loop] cls ' clear screen
print msg$
button #c, "Click Me", [clickMe] 'create a button with handle and goto [tag]
wait
 
[clickMe]
clicks = clicks + 1
msg$ = "Button has been clicked ";clicks;" times"
goto [loop]</syntaxhighlight>
 
=={{header|Rust}}==
{{libheader|iced}}
<syntaxhighlight lang="rust">use iced::{ // 0.2.0
button, Button, Column, Element, Length,
Text, Sandbox, Settings, Space,
};
 
#[derive(Debug, Copy, Clone)]
struct Pressed;
struct Simple {
value: i32,
button: button::State,
}
 
impl Sandbox for Simple {
type Message = Pressed;
 
fn new() -> Simple {
Simple {
value: 0,
button: button::State::new(),
}
}
 
fn title(&self) -> String {
"Simple Windowed Application".into()
}
 
fn view(&mut self) -> Element<Self::Message> {
Column::new()
.padding(20)
.push({
let text = match self.value {
0 => "there have been no clicks yet".into(),
1 => "there has been 1 click".into(),
n => format!("there have been {} clicks", n),
};
Text::new(text).size(24)
}).push(
Space::with_height(Length::Fill)
).push(
Button::new(&mut self.button, Text::new("Click Me!"))
.on_press(Pressed)
).into()
}
 
fn update(&mut self, _: Self::Message) {
self.value += 1;
}
}
 
fn main() {
let mut settings = Settings::default();
settings.window.size = (600, 400);
Simple::run(settings).unwrap();
}</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<syntaxhighlight lang="scala">import scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication }
import scala.swing.event.ButtonClicked
 
object SimpleApp extends SimpleSwingApplication {
def top = new MainFrame {
contents = new BorderPanel {
var nClicks = 0
 
val (button, label) = (new Button { text = "click me" },
new Label { text = "There have been no clicks yet" })
 
layout(button) = BorderPanel.Position.South
layout(label) = BorderPanel.Position.Center
listenTo(button)
reactions += {
case ButtonClicked(_) =>
nClicks += 1
label.text = s"There have been ${nClicks} clicks"
}
}
}
}</syntaxhighlight>
 
 
=={{header|Scratch}}==
<syntaxhighlight lang="scratch">
when flag clicked # when program is run
set counter to "0" # initialize counter object to zero
set message to "There have been no clicks"
show variable message # show the message object
 
when this sprite clicked # when button clicked
hide message # hide the initial message
change counter by 1 # increment the counter object
</syntaxhighlight>
 
'''Comments and Description:'''<br>
The Scratch IDE has a GUI drag and drop interface.
The program above is has both graphic and text objects.
The 'message' and 'counter' variables coded above are also graphic objects.
They are set to "large readout" rather than slider or normal.
The (implied) 'sprite' has a 'costume' set to "button".
 
[https://www.melellington.com/simplewindow/scratchoutput.jpg Scratch-Output]
 
=={{header|Sidef}}==
===Gtk2===
<syntaxhighlight lang="ruby">require('Gtk2') -> init
 
# Window.
var window = %s<Gtk2::Window>.new
window.signal_connect('destroy' => { %s<Gtk2>.main_quit })
 
# VBox.
var vbox = %s<Gtk2::VBox>.new(0, 0)
window.add(vbox)
 
# Label.
var label = %s<Gtk2::Label>.new('There have been no clicks yet.')
vbox.add(label)
 
# Button.
var count = 0
var button = %s<Gtk2::Button>.new(' Click Me ')
vbox.add(button)
button.signal_connect('clicked' => {
label.set_text(++count)
})
 
# Show.
window.show_all
 
# Main loop.
%s<Gtk2>.main</syntaxhighlight>
 
===Gtk3===
<syntaxhighlight lang="ruby">use('Gtk3 -init')
 
# Window.
var window = %O'Gtk3::Window'.new
window.signal_connect('destroy' => { %O'Gtk3'.main_quit })
 
# VBox.
var vbox = %O'Gtk3::VBox'.new(0, 0)
window.add(vbox)
 
# Label.
var label = %O'Gtk3::Label'.new('There have been no clicks yet.')
vbox.add(label)
 
# Button.
var count = 0
var button = %O'Gtk3::Button'.new(' Click Me ');
vbox.add(button)
button.signal_connect('clicked' => {
label.set_text(++count)
})
 
# Show.
window.show_all
 
# Main loop.
%O'Gtk3'.main</syntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">|top clickCount lh button|
 
clickCount := 0.
lh := ValueHolder with:'There have been no clicks yet'.
 
top := StandardSystemView label:'Rosetta Simple Window'.
top extent:300@100.
top add:((Label new labelChannel:lh) origin: 0 @ 10 corner: 1.0 @ 40).
top add:((button := Button label:'Eat Me') origin: 10 @ 50 corner: 100 @ 80).
 
button action:[
clickCount := clickCount + 1.
lh value: ('number of clicks: %1' bindWith:clickCount)
].
 
top open</syntaxhighlight>
 
=={{header|Standard ML}}==
Works with PolyML
<syntaxhighlight lang="standard ml">open XWindows ;
open Motif ;
val countWindow = fn () =>
let
val ctr = ref 0;
val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 300, XmNheight 150 ] ;
val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ;
val frame = XmCreateForm main "frame" [XmNwidth 390, XmNheight 290 ] ;
val text = XmCreateLabel frame "show" [XmNlabelString "No clicks yet" ] ;
val buttn = XmCreateDrawnButton frame "press" [XmNwidth 75 , XmNheight 30 ,
XmNlabelString "Click me" ,
XmNbottomAttachment XmATTACH_POSITION,XmNbottomPosition 98 ] ;
val report = fn (w,c,t) =>
(XtSetValues text [XmNlabelString (Int.toString (ctr:= !ctr +1; !ctr)) ] ; t )
in
(
XtSetCallbacks buttn [ (XmNactivateCallback , report) ] XmNarmCallback ;
XtManageChildren [ text,buttn ] ;
XtManageChildren [ frame ] ;
XtManageChild main ;
XtRealizeWidget shell
)
end;
</syntaxhighlight>
call
countWindow () ;
 
 
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
pack [label .l -text "There have been no clicks yet"]
set count 0
Line 922 ⟶ 3,680:
proc upd {} {
.l configure -text "Number of clicks: [incr ::count]"
}</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
Line 928 ⟶ 3,686:
The Ti-89 does not have general onscreen buttons; this program uses the OK/Cancel choice of a dialog box to implement the UI.
 
<syntaxhighlight lang="ti89b">Prgm
<pre style="font-family:'TI Uni'">Prgm
Local clicks
0 → clicks
Line 939 ⟶ 3,697:
clicks + 1 → clicks
EndWhile
EndPrgm</presyntaxhighlight>
 
=={{header|Unicon}}==
 
<syntaxhighlight lang="unicon">
import gui
$include "guih.icn"
 
class SimpleApp : Dialog (label)
 
# -- automatically called when the dialog is created
method component_setup()
# create and add the label
label := Label("label=There have been no clicks yet","pos=50%,33%", "align=c,c")
add (label)
 
# create and add the button
button := TextButton("label=Click me", "pos=50%,66%", "align=c,c")
button.connect(self, "clicked", ACTION_EVENT)
add (button)
 
# some cosmetic settings for the window
attrib("size=180,70", "bg=light gray")
end
 
method clicked ()
static count := 0
count +:= 1
label.set_label ("Clicked " || count || " times")
end
end
 
procedure main()
local d := SimpleApp ()
d.show_modal()
end
</syntaxhighlight>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">// GTK 4
public class Example : Gtk.Application {
public Example() {
Object(application_id: "my.application",
flags: ApplicationFlags.FLAGS_NONE);
activate.connect(() => {
var window = new Gtk.ApplicationWindow(this);
var box = new Gtk.Box(Gtk.Orientation.VERTICAL, 20);
var label = new Gtk.Label("There have been no clicks yet");
var button = new Gtk.Button.with_label("click me");
var clicks = 0;
button.clicked.connect(() => {
clicks++;
label.label = "Button clicked " + clicks.to_string() + " times";
});
box.append(label);
box.append(button);
window.set_child(box);
window.present();
});
}
public static int main(string[] argv) {
return new Example().run(argv);
}
}</syntaxhighlight>
 
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">Reg_Set(10, "There have been no clicks yet")
<pre>
Reg_Set(10, "There have been no clicks yet")
#1 = 0
repeat (ALL) {
Line 955 ⟶ 3,775:
Reg_Set(10, "Clicked", INSERT)
Reg_Set(10, " times", APPEND)
}</syntaxhighlight>
 
=={{header|Visual Basic}}==
In VB, windows are usually created in the IDE. The generated code is hidden from the user unless viewed outside of VB. For the sake of this task, I have included that code, but normally it is hidden from the programmer.
 
<syntaxhighlight lang="vb">VERSION 5.00
Begin VB.Form Form2
Caption = "There have been no clicks yet"
ClientHeight = 2940
ClientLeft = 60
ClientTop = 600
ClientWidth = 8340
LinkTopic = "Form1"
ScaleHeight = 2940
ScaleWidth = 8340
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton Command1
Caption = "Click me!"
Height = 495
Left = 3600
TabIndex = 0
Top = 1200
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'-----user-written code begins here; everything above this line is hidden in the GUI-----
Private clicked As Long
 
Private Sub Command1_Click()
clicked = clicked + 1
Me.Caption = clicked & " clicks."
End Sub
</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import ui
import gx
 
[heap]
struct App {
mut:
window &ui.Window = unsafe {nil}
counter string = "No clicks yet" // will contain number count
}
 
fn main() {
mut app := &App{}
app.window = ui.window(
width: 200
height: 40
title: "Counter"
mode: .resizable
layout: ui.row(
spacing: 5
margin_: 10
widths: ui.stretch
heights: ui.stretch
children: [
ui.label(
id: "num"
text: &app.counter //refer to struct App
),
ui.button(
text: "Click me"
bg_color: gx.light_gray
radius: 5
border_color: gx.gray
on_click: app.btn_click //refer to function below
),
]
)
)
ui.run(app.window)
}
 
fn (mut app App) btn_click(btn &ui.Button) {
mut lbl := app.window.get_or_panic[ui.Label]("num") //"num" is id of label
app.counter = (app.counter.int() + 1).str() //change to string for label display
lbl.set_text(app.counter)
}
</syntaxhighlight>
 
=={{header|Web 68}}==
<syntaxhighlight lang="web68">@1Introduction.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Licence as published by
the Free Software Foundation, either version 3 of the Licence, or
(at your option) any later version.
 
Copyright (c) 2012 Sian Mountbatten.
 
@m cvs simpleapp = "$Id: $"
 
@a@<Prelude@>
BEGIN
@<Included declarations@>
@<Plain values in the outer reach@>
@<Names in the outer reach@>
@<Procedures in the outer reach@>
@<Logic in the outer reach@>
END
@<Postlude@>
 
@ The local compiler requires a special prelude.@^system dependencies@>
 
@<Prel...@>=
PROGRAM simpleapp CONTEXT VOID
USE @<Library preludes@>
 
@ And a special postlude.@^system dependencies@>
 
@<Post...@>=
FINISH
 
@ The program requires the predefined forms and the standard prelude.
 
@<Library...@>=
simpleapp fd,standard
 
@ This Web 68 file provides the Xforms prelude.
 
@iforms.w@>
 
@1Initialisation.
The initial processing consists of initialising the Xforms library.
 
@<Logic...@>=
open(argf,"",arg channel);
fl initialize(argc,argv,"simpleapp",NIL,0);
 
@ Declare the !REF FILE!.
 
@<Names...@>=
FILE @!argf;
 
@1Main processing.
The form is created in !simpleapp fd! the source code of which is 108 lines long.
Firstly, define the callback for the button.
 
@<Proc...@>=
button cb:=(REF FLOBJECT obj,INT data)VOID:
(
clicks +:= 1;
fl set object label(text box OF click form,whole(clicks,0)+" click"+
(clicks=1|""|"s")+" on the button")
);
 
@ Declare !clicks!.
 
@<Plain...@>=
INT clicks:=0;
 
@ Create the form, show it and hand control to the Xforms library.
 
@<Logic...@>=
click form:=create form click;
fl show form(click OF click form,fl place center,fl full border,"SimpleApp");
fl do forms
 
@ Declare the form.
 
@<Names...@>=
REF FDCLICK click form;
 
@1Macro declarations.
All the macros used in the program are declared here.
 
@<Include...@>=
macro fl do forms;
macro fl initialize;
macro fl set object label;
macro fl show form;
 
@ To compile the program, use this command:
<pre>
ca -l mod -l forms simpleapp.w68
</pre>
The predefined form will have been compiled with this command:
<pre>
ca -m mod simpleappfd.w68
</pre>
The predefined form was created by the <b>fdesign</b> program for the Xforms library,
and the resulting form definition file was converted to Web 68 by the program
<b>fdtow68</b>.</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "input" for Mouse
import "dome" for Window
 
class SimpleWindowedApplication {
construct new(width, height) {
Window.title = "Simple windowed application"
_fore = Color.white
_clicks = 0
}
 
init() {
drawControls()
}
 
update() {
if (Mouse["left"].justPressed && insideButton) _clicks = _clicks + 1
}
 
draw(alpha) {
drawControls()
}
 
insideButton {
var p = Mouse.position
return p.x >= 120 && p.x <= 200 && p.y >= 90 && p.y <= 170
}
 
drawControls() {
Canvas.cls()
if (_clicks == 0) {
Canvas.print("There have been no clicks yet", 40, 40, _fore)
} else if (_clicks == 1) {
Canvas.print("The button has been clicked once", 30, 40, _fore)
} else {
Canvas.print("The button has been clicked %(_clicks) times", 10, 40, _fore)
}
Canvas.rectfill(120, 90, 80, 80, Color.red)
Canvas.rect(120, 90, 80, 80, Color.blue)
Canvas.print("click me", 130, 125, _fore)
}
}
 
var Game = SimpleWindowedApplication.new(600, 600)</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include c:\cxpl\stdlib; \standard library provides mouse routines, etc.
def Ww=40, Wh=12, Wx=(80-Ww)/2, Wy=(25-Wh)/2; \window width, etc.
def Bw=11, Bh=4, Bx=Wx+(Ww-Bw)/2, By=Wy+3*(Wh-Bh)/4; \button size & position
int Clicks, Mx, My; \number of clicks and mouse coordinates
 
[ShowCursor(false); \turn off flashing cursor
Attrib($1F); \bright white characters on blue
SetWind(Wx, Wy, Wx+Ww, Wy+Wh, 2, true); \blue window with no scroll
DrawBox(Wx, Wy, Wx+Ww, Wy+Wh, 3); \draw borders
Cursor(Wx+5, Wy+3); Text(6, "There have been no clicks yet.");
DrawBox(Bx, By, Bx+Bw, By+Bh, 0); \draw button
Cursor(Bx+2, By+2); Text(6, "Click me");
 
OpenMouse;
ShowMouse(true);
Clicks:= 0;
repeat if GetMouseButton(0) then \left button down
[while GetMouseButton(0) do []; \wait for release
Mx:= GetMousePosition(0) / 8; \character coordinates
My:= GetMousePosition(1) / 8;
if Mx>=Bx & Mx<=Bx+Bw & My>=By & My<=By+Bh then
[Clicks:= Clicks+1; \mouse pointer is on the button
Cursor(Wx+4, Wy+3);
Text(6, "Times button has been clicked: ");
IntOut(6, Clicks);
];
];
until ChkKey; \keystroke terminates program
SetVid(3); \turn off mouse and turn on flashing cursor
]</syntaxhighlight>
 
=={{header|Yorick}}==
Yorick does not include a GUI toolkit. However, it does provide a plotting system that can emulate some basic GUI features, such as buttons and labels. The above sample uses a built-in library "button.i", which is itself written in Yorick.
 
<syntaxhighlight lang="yorick">#include "button.i"
 
window, 0;
btn_click = Button(text="click me", x=.395, y=.65, dx=0.04368, dy=0.0091);
btn_quit = Button(text="quit", x=.395, y=.6, dx=0.02184, dy=0.0091);
count = 0;
msg = "There have been no clicks yet";
finished = 0;
do {
fma;
plt, msg, .395, .7, justify="CH";
button_plot, btn_click;
button_plot, btn_quit;
xy = mouse(0, 0, "");
if(button_test(btn_click, xy(1), xy(2))) {
count++;
msg = swrite(format="Number of clicks: %d", count);
} else if(button_test(btn_quit, xy(1), xy(2))) {
finished = 1;
winkill, 0;
}
} while(!finished);</syntaxhighlight>
 
{{omit from|ACL2}}
{{omit from|AWK}}
{{omit from|Batch File|Does not have access to GUI functions.}}
{{omit from|EasyLang}}
{{omit from|GUISS}}
{{omit from|Logtalk}}
{{omit from|Maxima}}
{{Omit From|Metafont}}
{{omit from|ML/I}}
{{omit from|PARI/GP}}
{{omit from|PHP}}
{{omit from|Retro}}
{{omit from|SQL PL|It does not handle GUI}}
{{omit from|ZX Spectrum Basic|Does not use a mouse}}
9,482

edits