GUI enabling/disabling of controls: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(40 intermediate revisions by 20 users not shown)
Line 6:
{{omit from|Blast}}
{{omit from|Brainf***}}
{{omit from|Commodore BASIC}}
{{omit from|GUISS|Can only do what the installed applications can do}}
{{omit from|Integer BASIC|no concept of a GUI}}
Line 15 ⟶ 16:
{{omit from|PostScript}}
{{omit from|Retro}}
{{omit from|SQL PL|It does not handle GUI}}
 
In addition to fundamental [[GUI component interaction]], an application should
Line 50 ⟶ 52:
 
disabling.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Fixed;
with Gtk.Main;
with Gtk.Handlers;
Line 218 ⟶ 220:
 
Gtk.Main.Main;
end Disabling;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">GUI, Add, Edit, w150 number vValue gEnableDisable, 0 ; Number specifies a numbers-only edit field. g<Subroutine> specifies a subroutine to run when the value of control changes.
GUI, Add, button,, Increment
GUI, Add, button, xp+70 yp, Decrement ; xp+70 and yp are merely positioning options
Line 265 ⟶ 267:
GuiClose:
ExitApp
; Ensures the script ends when the GUI is closed.</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BaCon}}===
This code requires BaCon 4.0.1 or higher.
<syntaxhighlight lang="bacon">OPTION GUI TRUE
PRAGMA GUI gtk3
 
gui = GUIDEFINE(" \
{ type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=200 } \
{ type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
{ type=SPIN_BUTTON name=spin parent=box numeric=TRUE } \
{ type=BUTTON_BOX name=bbox parent=box } \
{ type=BUTTON name=increment parent=bbox callback=clicked label=\"Increment\" } \
{ type=BUTTON name=decrement parent=bbox callback=clicked label=\"Decrement\" } ")
 
CALL GUISET(gui, "spin", "adjustment", gtk_adjustment_new(0, 0, 10, 1, 1, 0))
CALL GUISET(gui, "decrement", "sensitive", FALSE)
 
DECLARE input TYPE FLOATING
 
WHILE TRUE
 
CALL GUIGET(gui, "spin", "value", &input)
SELECT GUIEVENT$(gui)
CASE "increment"
INCR input
CASE "decrement"
DECR input
CASE "window"
BREAK
ENDSELECT
CALL GUISET(gui, "spin", "value", input)
 
CALL GUISET(gui, "decrement", "sensitive", IIF(input <= 0, FALSE, TRUE))
CALL GUISET(gui, "increment", "sensitive", IIF(input > 9, FALSE, TRUE))
CALL GUISET(gui, "spin", "sensitive", IIF(input = 0, TRUE, FALSE))
 
WEND</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
ES_NUMBER = 8192
Line 305 ⟶ 345:
SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
SYS "SetDlgItemInt", !form%, 101, number% - 1, 1
ENDPROC</langsyntaxhighlight>
{{out}}
<p>
Line 315 ⟶ 355:
<pre>file main.c</pre>
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
Line 394 ⟶ 434:
EnableWindow( GetDlgItem(hwnd,IDC_INCREMENT), n<MAX_VALUE );
EnableWindow( GetDlgItem(hwnd,IDC_DECREMENT), n>MIN_VALUE );
}</langsyntaxhighlight>
 
<pre>file resource.h</pre>
 
<langsyntaxhighlight lang="c">#define IDD_DLG 101
#define IDC_INPUT 1001
#define IDC_INCREMENT 1002
#define IDC_DECREMENT 1003
#define IDC_QUIT 1004</langsyntaxhighlight>
 
<pre>file resource.rc</pre>
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include "resource.h"
 
Line 419 ⟶ 459:
PUSHBUTTON "Quit", IDC_QUIT, 117, 25, 30, 14
RTEXT "Value:", -1, 10, 8, 20, 8
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
Using Windows Forms; compile with csc -t:winexe Program.cs (on MS.NET) or gmcs -t:winexe Program.cs (on Mono)
<syntaxhighlight lang="csharp">using System;
using System.ComponentModel;
using System.Windows.Forms;
 
class RosettaInteractionForm : Form
{
 
// Model used for DataBinding.
// Notifies bound controls about Value changes.
class NumberModel: INotifyPropertyChanged
{
// initialize event with empty delegate to avoid checks on null
public event PropertyChangedEventHandler PropertyChanged = delegate {};
 
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
// Notify bound control about value change
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
 
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
//MaskedTextBox is a TextBox variety with built-in input validation
var tbNumber = new MaskedTextBox
{
Mask="0000", // allow 4 decimal digits only
ResetOnSpace = false, // don't enter spaces
Dock = DockStyle.Top // place at the top of form
};
// bound TextBox.Text to NumberModel.Value;
tbNumber.DataBindings.Add("Text", model, "Value");
var enabledIfZero = new Binding("Enabled", model, "Value");
EnableControlWhen(tbNumber, value => value == 0);
 
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
EnableControlWhen(btIncrement, value => value < 10);
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
EnableControlWhen(btDecrement, value => value > 0);
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
}
 
// common part of creating bindings for Enabled property
void EnableControlWhen(Control ctrl, Func<int, bool> predicate)
{
// bind Control.Enabled to NumberModel.Value
var enabledBinding = new Binding("Enabled", model, "Value");
// Format event is called when model value should be converted to Control value.
enabledBinding.Format += (sender, args) =>
{
// Enabled property is of bool type.
if (args.DesiredType != typeof(bool)) return;
// set resulting value by applying condition
args.Value = predicate((int)args.Value);
};
// as a result, control will be enabled if predicate returns true
ctrl.DataBindings.Add(enabledBinding);
}
 
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}</syntaxhighlight>
 
=={{header|C++}}==
with Qt 4.4, creating project file with qmake -project, Makefile with qmake -o Makefile <projectfile> and finally make
<pre>file task.h</pre>
<langsyntaxhighlight lang="cpp">#ifndef TASK_H
#define TASK_H
 
Line 453 ⟶ 578:
QHBoxLayout *lowerPart ;
} ;
#endif</langsyntaxhighlight>
 
<pre>file task.cpp</pre>
<langsyntaxhighlight lang="cpp">#include <QtGui>
#include <QString>
#include "task.h"
Line 509 ⟶ 634:
number-- ;
entryField->setText( QString("%1").arg( number )) ;
}</langsyntaxhighlight>
 
<pre>main.cpp</pre>
<langsyntaxhighlight lang="cpp">#include <QApplication>
#include "task.h"
 
Line 520 ⟶ 645:
theWidget.show( ) ;
return app.exec( ) ;
}</langsyntaxhighlight>
 
=={{header|C_sharp|C#}}==
Using Windows Forms; compile with csc -t:winexe Program.cs (on MS.NET) or gmcs -t:winexe Program.cs (on Mono)
<lang c_sharp>using System;
using System.ComponentModel;
using System.Windows.Forms;
 
class RosettaInteractionForm : Form
{
 
// Model used for DataBinding.
// Notifies bound controls about Value changes.
class NumberModel: INotifyPropertyChanged
{
// initialize event with empty delegate to avoid checks on null
public event PropertyChangedEventHandler PropertyChanged = delegate {};
 
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
// Notify bound control about value change
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
 
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
//MaskedTextBox is a TextBox variety with built-in input validation
var tbNumber = new MaskedTextBox
{
Mask="0000", // allow 4 decimal digits only
ResetOnSpace = false, // don't enter spaces
Dock = DockStyle.Top // place at the top of form
};
// bound TextBox.Text to NumberModel.Value;
tbNumber.DataBindings.Add("Text", model, "Value");
var enabledIfZero = new Binding("Enabled", model, "Value");
EnableControlWhen(tbNumber, value => value == 0);
 
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
EnableControlWhen(btIncrement, value => value < 10);
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
EnableControlWhen(btDecrement, value => value > 0);
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
}
 
// common part of creating bindings for Enabled property
void EnableControlWhen(Control ctrl, Func<int, bool> predicate)
{
// bind Control.Enabled to NumberModel.Value
var enabledBinding = new Binding("Enabled", model, "Value");
// Format event is called when model value should be converted to Control value.
enabledBinding.Format += (sender, args) =>
{
// Enabled property is of bool type.
if (args.DesiredType != typeof(bool)) return;
// set resulting value by applying condition
args.Value = predicate((int)args.Value);
};
// as a result, control will be enabled if predicate returns true
ctrl.DataBindings.Add(enabledBinding);
}
 
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}</lang>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">type
TForm1 = class(TForm)
MaskEditValue: TMaskEdit; // Set Editmask on: "99;0; "
Line 638 ⟶ 678:
begin
MaskEditValue.Text := IntToStr(Succ(StrToIntDef(Trim(MaskEditValue.Text), 0)));
end;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">using fwt
using gfx
 
Line 708 ⟶ 749:
}.open
}
}</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
<lang FreeBASIC>
#Include "windows.bi"
 
Line 750 ⟶ 790:
 
End
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum 1
_inputFld
_incBtn
_decBtn
end enum
 
void local fn BuildWindow
window _window, @"GUI enabling/disabling of controls", (0,0,350,150), NSWindowStyleMaskTitled
textfield _inputFld,, @"0", (160,78,30,21)
ControlSetAlignment( _inputFld, NSTextAlignmentCenter )
button _incBtn,,, @"Increment", (75,43,101,32)
button _decBtn, NO,, @"Decrement", (174,43,101,32)
end fn
 
void local fn InputAction
long value = fn ControlIntegerValue( _inputFld )
if ( value < 0 or value > 10 ) then value = 0
textfield _inputFld,, str(value)
select ( value )
case 0
TextFieldSetEditable( _inputFld, YES )
button _incBtn, YES
button _decBtn, NO
case 10
TextFieldSetEditable( _inputFld, NO )
WindowMakeFirstResponder( _window, 0 )
button _incBtn, NO
button _decBtn, YES
case else
TextFieldSetEditable( _inputFld, NO )
WindowMakeFirstResponder( _window, 0 )
button _incBtn, YES
button _decBtn, YES
end select
end fn
 
void local fn IncrementAction
long value = fn ControlIntegerValue( _inputFld ) + 1
textfield _inputFld,, str(value)
TextFieldSetEditable( _inputFld, NO )
WindowMakeFirstResponder( _window, 0 )
if ( value >= 10 ) then button _incBtn, NO
if ( value > 0 ) then button _decBtn, YES
end fn
 
void local fn DecrementAction
long value = fn ControlIntegerValue( _inputFld ) - 1
textfield _inputFld,, str(value)
if ( value < 10 ) then button _incBtn, YES
if ( value == 0 )
button _decBtn, NO
TextFieldSetEditable( _inputFld, YES )
end if
end fn
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _inputFld : fn InputAction
case _incBtn : fn IncrementAction
case _decBtn : fn DecrementAction
end select
end select
end fn
 
fn BuildWindow
 
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
[[File:GUIEnableDisableControls350FB.png]]
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">hValueBox As ValueBox 'We need a ValueBox
hButton0 As Button 'We need a button
hButton1 As Button 'We need another button
 
Public Sub Form_Open()
 
With Me 'Set the Form's Properties..
.height = 95 'Set the Height
.Width = 350 'Set the Width
.Arrangement = Arrange.Vertical 'Arrange items vertically
.Padding = 5 'Border area
.Title = "GUI enable/disable" 'Title displayed on the Form
End With
 
hValueBox = New ValueBox(Me) As "ValBox" 'Add a ValueBox to the Form as Event 'ValBox'
 
With hValueBox 'Set the ValueBox's Properties..
.Expand = True 'Expand the ValueBox
.Value = 0 'Set it's value to 0
End With
 
hButton0 = New Button(Me) As "ButtonInc" 'Add a Button to the form as Event "ButtonInc"
 
With hButton0 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Increment" 'Add Text (The '&' adds a keyboard shortcut)
End With
 
hButton1 = New Button(Me) As "ButtonDec" 'Add a Button to the form as Event "ButtonDec"
 
With hButton1 'Set the Button's Properties..
.Height = 28 'Set the Height
.Text = "&Decrement" 'Add Text (The '&' adds a keyboard shortcut)
.Enabled = False 'Disable the button
End With
 
End
 
Public Sub ButtonInc_Click() 'When the 'Increment' Button is clicked..
 
hValueBox.Value += 1 'Increase the Value in the ValueBox by 1
Checks
 
End
 
Public Sub ButtonDec_Click() 'When the 'Decrement' Button is clicked..
 
hValueBox.Value -= 1 'Increase the Value in the ValueBox by 1
Checks
 
End
 
Public Sub Checks() 'Checks the values to see which controls to en/disable
 
If hValueBox.Value = 0 Then 'If the ValueBox = 0 then..
hValueBox.enabled = True 'Enable the control
Else 'Else..
hValueBox.enabled = False 'Disable the control
End If
 
If hValueBox.Value > 9 Then 'If the ValueBox greater than 9 then..
hButton0.enabled = False 'Disable the control
Else 'Else..
hButton0.enabled = True 'Enable the control
End If
 
If hValueBox.Value < 1 Then 'If the ValueBox less than 1 then..
hButton1.enabled = False 'Disable the control
Else 'Else..
hButton1.enabled = True 'Enable the control
End If
 
End
 
Public Sub ValBox_Leave() 'When the mouse leaves the ValueBox..
 
Checks 'Rune the Checks routine
 
End</syntaxhighlight>
 
=={{header|Go}}==
{{libheader|Gotk3}}
Loosely based on the Vala entry.
<syntaxhighlight lang="go">package main
 
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
 
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
 
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
 
func processState(i int64, entry *gtk.Entry, ib, db *gtk.Button) {
if i == 0 {
entry.SetSensitive(true)
} else {
entry.SetSensitive(false)
}
if i < 10 {
ib.SetSensitive(true)
} else {
ib.SetSensitive(false)
}
if i > 0 {
db.SetSensitive(true)
} else {
db.SetSensitive(false)
}
}
 
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
 
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
 
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
 
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
 
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0") // initialize to zero
entry.SetSensitive(true)
 
// button to increment
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.SetSensitive(true)
 
// button to decrement
db, err := gtk.ButtonNewWithLabel("Decrement")
check(err, "Unable to create decrement button:")
db.SetSensitive(false)
 
entry.Connect("activate", func() {
// read and validate the entered value
str, _ := entry.GetText()
i, ok := validateInput(window, str)
if !ok {
entry.SetText("0")
}
processState(i, entry, ib, db)
})
 
ib.Connect("clicked", func() {
// read the entered value
str, _ := entry.GetText()
i, _ := validateInput(window, str)
i++
entry.SetText(strconv.FormatInt(i, 10))
processState(i, entry, ib, db)
})
 
db.Connect("clicked", func() {
// read the entered value
str, _ := entry.GetText()
i, _ := validateInput(window, str)
i--
entry.SetText(strconv.FormatInt(i, 10))
processState(i, entry, ib, db)
})
 
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(db, false, false, 2)
window.Add(box)
 
window.ShowAll()
gtk.Main()
}</syntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 759 ⟶ 1,091:
This uses the Unicon specific graphics library.
 
<syntaxhighlight lang="unicon">
<lang Unicon>
import gui
$include "guih.icn"
Line 847 ⟶ 1,179:
w.show_modal ()
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
'''J 8.x'''
<langsyntaxhighlight lang="j">task_run=: wd bind (noun define)
pc task nosize;
cc decrement button;cn "Decrement";
Line 876 ⟶ 1,208:
task_decrement_button=:verb define
update Value=: ": _1 + 0 ". Value
)</langsyntaxhighlight>
 
'''J 6.x'''
<langsyntaxhighlight Jlang="j">task_run=: wd bind (noun define)
pc task nosize;
xywh 6 30 48 12;cc decrement button;cn "-";
Line 902 ⟶ 1,234:
task_decrement_button=:verb define
update Value=: ": _1 + 0 ". Value
)</langsyntaxhighlight>
 
Example use:
 
<syntaxhighlight lang="text"> task_run''</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Swing}}
{{works with|AWT}}
<langsyntaxhighlight lang="java">import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Line 1,063 ⟶ 1,395:
new Interact().setVisible(true);
}
}</langsyntaxhighlight>
 
 
{{libheader|JavaFX}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">
import javafx.application.Application;
import javafx.beans.property.LongProperty;
Line 1,124 ⟶ 1,456:
increment.setOnAction(event-> inputValue.set(inputValue.get() + 1));
 
// incr-button is disabled when input is >= 010
increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10));
 
Line 1,147 ⟶ 1,479:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
using Tk
w = Toplevel("GUI enabling/disabling")
Line 1,200 ⟶ 1,532:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{libheader|JavaFX}}
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.2.21
 
import javafx.application.Application
import javafx.beans.property.SimpleLongProperty
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.TextField
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.stage.Stage
import javafx.util.converter.NumberStringConverter
import javafx.event.ActionEvent
 
val digits = Regex("[0-9]*")
 
class InteractFX : Application() {
 
override fun start(stage: Stage) {
val input = object : TextField("0") {
// only accept numbers as input
override fun replaceText(start: Int, end: Int, text: String) {
if (text.matches(digits)) super.replaceText(start, end, text)
}
 
// only accept numbers on copy + paste
override fun replaceSelection(text: String) {
if (text.matches(digits)) super.replaceSelection(text)
}
}
 
// when the textfield is empty, replace text with "0"
input.textProperty().addListener { _, _, newValue ->
if (newValue == null || newValue.trim().isEmpty()) input.text = "0"
}
 
// get a bi-directional bound long-property of the input value
val inputValue = SimpleLongProperty()
input.textProperty().bindBidirectional(inputValue, NumberStringConverter())
 
// textfield is disabled when the current value is other than "0"
input.disableProperty().bind(inputValue.isNotEqualTo(0))
 
val increment = Button("Increment")
increment.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() + 1) }
 
// increment button is disabled when input is >= 10
increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10))
 
val decrement = Button("Decrement")
decrement.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() - 1) }
// decrement button is disabled when input is <= 0
decrement.disableProperty().bind(inputValue.lessThanOrEqualTo(0))
 
// layout
val root = VBox()
root.children.add(input)
val buttons = HBox()
buttons.children.addAll(increment, decrement)
root.children.add(buttons)
 
stage.scene = Scene(root)
stage.sizeToScene()
stage.show()
}
}
 
fun main(args: Array<String>) {
Application.launch(InteractFX::class.java, *args)
}</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">nomainwin
textbox #demo.val, 20, 50, 90, 24
button #demo.dec, "Decrement", [btnDecrement], UL, 20, 90, 90, 24
Line 1,282 ⟶ 1,688:
#demo.val "!disable"
end if
End Sub</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Line 1,298 ⟶ 1,704:
 
4. Select Object->Card Script and enter the following to handle enabling the buttons.
<langsyntaxhighlight LiveCodelang="livecode">command enableButtons v
switch
case v <= 0
Line 1,315 ⟶ 1,721:
put v into fld "Field1"
end switch
end enableButtons</langsyntaxhighlight>
 
For the increment button, click on Button 1 (in edit mode) and the select "code" from the toolbar and enter the following to handle clicks<langsyntaxhighlight LiveCodelang="livecode">on mouseUp
put field "Field1" into x
add 1 to x
enableButtons x
end mouseUp</langsyntaxhighlight>
 
Repeat for Button 2 (note we are subtracting here)<langsyntaxhighlight LiveCodelang="livecode">on mouseUp
put field "Field1" into x
subtract 1 from x
enableButtons x
end mouseUp</langsyntaxhighlight>
 
Finally add the code to handle keyboard entry in text field's code. Note this code prevents entering digits outside 0-9 and limits the value between 0 and 10.<langsyntaxhighlight LiveCodelang="livecode">on rawKeyDown k
if numToChar(k) is among the items of "1,2,3,4,5,6,7,8,9,0" then
if (numToChar(k) + the text of me) <= 10 then
Line 1,337 ⟶ 1,743:
pass rawKeyDown
end if
end rawKeyDown</langsyntaxhighlight>
 
Switch back to the form, and enter run mode to execute.
Line 1,343 ⟶ 1,749:
n.b. Open stack handlers would be prudent to initialise the default value and button states if this were to be saved for standalone execution.
 
=={{header|MathematicaM2000 Interpreter}}==
Normally a function can't call other except something global or something defined in function (local), or for member functions in Group object, they can call other members public or private at same level or deeper but then only the public members. Using Call Local we call functions like function's part. When an event service function called (by event), interpreter provide the same name as the module's name, where form declared, so this call is a "local call". So a second local call inside event service function,also provide same name. So global local1 called as local, so code executed as part of CheckIt (but without same "current" stack, and other specific to execution object properties). Modules, functions, threads, events are all executed on "execution objects" which carries the execution code.
<lang mathematica>Manipulate[Null, {{value, 0},
 
<syntaxhighlight lang="m2000 interpreter">
\\ this is global, but call as local in events, which means with local visibility for identifiers
\\ so thispos and this$ has to exist in caller 's context
 
Function Global Local1(new Feed$) {
\\ this function can be used from other Integer
\\ this$ and thispos, exist just before the call of this function
local sgn$
if feed$="" and this$="-" then thispos-- : exit
if left$(this$,1)="-" then sgn$="-": this$=mid$(this$, 2)
if this$<>Trim$(this$) then this$=Feed$ : thispos-- : exit
If Trim$(this$)="" then this$="0" : thispos=2 : exit
if instr(this$,"+")>0 and sgn$="-" then this$=filter$(this$, "+") : sgn$=""
if instr(this$,"-")>0 and sgn$="" then this$=filter$(this$, "-") : sgn$="-"
if filter$(this$,"0123456789")<>"" then this$=Feed$ : thispos-- : exit
if len(this$)>1 then While left$(this$,1)="0" {this$=mid$(this$, 2)}
this$=sgn$+this$
if this$="-0" then this$="-" : thispos=2
}
Module CheckIt {
Declare form1 form
Declare textbox1 textbox form form1
Declare buttonInc Button form form1
Declare buttonDec Button form form1
Method textbox1, "move", 2000,2000,4000,600
Method buttonInc, "move", 2000,3000,2000,600
Method buttonDec, "move", 4000,3000,2000,600
With textbox1,"vartext" as textbox1.value$, "Prompt", "Value:" ', "ShowAlways", True
With buttonInc,"Caption","Increment"
With buttonDec,"Caption","Decrement","Locked", True
textbox1.value$="0"
Function controlIncDec(what$){
With buttonInc, "locked", not val(what$)<10
With buttonDec, "locked", not val(what$)>0
}
finishEnter=false
Function TextBox1.ValidString {
\\ this function called direct from textbox
Read New &this$, &thispos
Call Local local1(textbox1.value$)
Call Local controlIncDec(this$)
}
Function TextBox1.Enable {
With TextBox1, "Enabled", true
finishEnter=false
}
Function TextBox1.Disable {
With TextBox1, "Enabled", false
finishEnter=true
}
Function TextBox1.Enter {
Call Local TextBox1.Disable()
}
Function buttonInc.Click {
if not finishEnter then Call Local TextBox1.Disable()
textbox1.value$=str$(val(textbox1.value$)+1, "")
if val(textbox1.value$)=0 then Call Local TextBox1.Enable()
}
function buttonDec.Click {
if not finishEnter then Call Local TextBox1.Disable()
textbox1.value$=str$(val(textbox1.value$)-1, "")
if val(textbox1.value$)=0 then Call Local TextBox1.Enable()
}
Call Local controlIncDec(textBox1.Value$)
Method form1, "show", 1
Declare form1 nothing
}
Checkit
 
</syntaxhighlight>
 
=={{header|Maple}}==
For this problem, you will need to open up Maple, go to the Components tab on the left, and insert a Text Area, and 2 Buttons. By right clicking each button, and clicking Component Properties, change one to Increase, and the other to Decrease. Then, click on 'Edit Content Changed Action". In the one labeled increase, type:
 
<syntaxhighlight lang="maple">
Increase();
</syntaxhighlight>
 
In the one labeled Decrease, type:
 
<syntaxhighlight lang="maple">
Decrease();
</syntaxhighlight>
 
Then, by clicking the 2 gears and opening up the start-up commands, enter this:
<syntaxhighlight lang="maple">
macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty);
with(Maplets[Elements]):
SP("Text",value,0);
Increase:=proc()
SP("Text",value,parse(GP("Text",value))+1);
if parse(GP("Text",value))>=10 then
SP("Button0", enabled, false);
else
SP("Button0", enabled, true);
end if;
if parse(GP("Text",value))<=0 then
SP("Button1", enabled, false);
else
SP("Button1", enabled, true);
end if;
end proc;
Decrease:=proc()
SP("Text",value,parse(GP("Text",value))-1);
if parse(GP("Text",value))<=0 then
SP("Button1", enabled, false);
else
SP("Button1", enabled, true);
end if;
if parse(GP("Text",value))>=10 then
SP("Button0", enabled, false);
else
SP("Button0", enabled, true);
end if;
end proc;
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Manipulate[Null, {{value, 0},
InputField[Dynamic[value], Number,
Enabled -> Dynamic[value == 0]] &},
Row@{Button["increment", value++, Enabled -> Dynamic[value < 10]],
Button["decrement", value--, Enabled -> Dynamic[value > 0]]}]</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">; file: gui-enable.lsp
; url: http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
; author: oofoe 2012-02-02
Line 1,398 ⟶ 1,925:
(gs:listen)
 
(exit)</langsyntaxhighlight>
 
Screenshot:
Line 1,405 ⟶ 1,932:
 
=={{header|Nim}}==
==={{libheader|Using Gtk2}}===
{{libheader|Gtk2}}
<lang nim>import
<syntaxhighlight lang="nim">import gtk2, strutils, glib2
 
var valu: int = 0
var chngd_txt_hndler: gulong = 0
proc thisDestroy(widget: PWidget, data: Pgpointer){.cdecl.} =
 
proc thisCheckBtns # forward declaration
 
proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} =
main_quit()
 
nim_init()
var window = window_new(gtk2.WINDOW_TOPLEVEL)
var content = vbox_new(TRUEtrue,10)
var hbox1 = hbox_new(TRUEtrue,10)
var entry_fld = entry_new()
entry_fld.set_text("0")
Line 1,428 ⟶ 1,952:
add(hbox1,btn_inc)
add(hbox1,btn_dec)
pack_start(content, entry_fld, TRUEtrue, TRUEtrue, 0)
pack_start(content, hbox1, TRUEtrue, TRUEtrue, 0)
pack_start(content, btn_quit, TRUEtrue, TRUEtrue, 0)
set_border_width(Windowwindow, 5)
add(window, content)
 
proc thisCheckBtns =
proc thisInc(widget: pWidget, data: pgpointer){.cdecl.} =
set_sensitive(btn_inc, valu < 10)
set_sensitive(btn_dec, valu > 0)
set_sensitive(entry_fld, valu == 0)
 
proc thisInc(widget: PWidget, data: Pgpointer){.cdecl.} =
inc(valu)
entry_fld.set_text($valu)
thisCheckBtns()
proc thisDec(widget: pWidgetPWidget, data: pgpointerPgpointer){.cdecl.} =
dec(valu)
entry_fld.set_text($valu)
thisCheckBtns()
 
proc thisTextChanged(widget: pWidgetPWidget, data: pgpointerPgpointer) {.cdecl.} =
#signal_handler_block(entry_fld, chngd_txt_hndler)
try:
valu = parseInt($entry_fld.get_text())
except EInvalidValueValueError:
entry_fld.set_text($valu = 0)
entry_fld.set_text($valu)
#signal_handler_unblock(entry_fld, chngd_txt_hndler)
#signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0)
thisCheckBtns()
 
proc thisCheckBtns =
set_sensitive(btn_inc, valu < 10)
set_sensitive(btn_dec, valu > 0)
set_sensitive(entry_fld, valu == 0)
 
discard signal_connect(window, "destroy",
SIGNAL_FUNC(thisDestroy), nil)
Line 1,468 ⟶ 1,988:
discard signal_connect(btn_dec, "clicked",
SIGNAL_FUNC(thisDec), nil)
chngd_txt_hndler =discard signal_connect(entry_fld, "changed",
SIGNAL_FUNC(thisTextChanged), nil)
 
show_all(window)
thisCheckBtns()
main()</langsyntaxhighlight>
 
==={{libheader|IUP}}===
===Using Gtk3 (gintro)===
<lang nim>import
{{libheader|gintro}}
 
<syntaxhighlight lang="nim">import strutils
import gintro/[glib, gobject, gtk, gio]
 
type Context = ref object
value: int
entry: Entry
btnIncr: Button
btnDecr: Button
 
#---------------------------------------------------------------------------------------------------
 
proc checkButtons(ctx: Context) =
ctx.btnIncr.setSensitive(ctx.value < 10)
ctx.btnDecr.setSensitive(ctx.value > 0)
ctx.entry.setSensitive(ctx.value == 0)
 
#---------------------------------------------------------------------------------------------------
 
proc onQuit(button: Button; window: ApplicationWindow) =
window.destroy()
 
#---------------------------------------------------------------------------------------------------
 
proc onIncr(button: Button; ctx: Context) =
inc ctx.value
ctx.entry.setText($ctx.value)
ctx.checkButtons()
 
#---------------------------------------------------------------------------------------------------
 
proc onDecr(button: Button; ctx: Context) =
dec ctx.value
ctx.entry.setText($ctx.value)
ctx.checkButtons()
 
#---------------------------------------------------------------------------------------------------
 
proc onEntryChange(entry: Entry; ctx: Context) =
try:
ctx.value = entry.text().parseInt()
except ValueError:
entry.setText($ctx.value)
 
#---------------------------------------------------------------------------------------------------
 
proc activate(app: Application) =
## Activate the application.
 
let window = app.newApplicationWindow()
window.setTitle("GUI controls")
 
let content = newBox(Orientation.vertical, 10)
content.setHomogeneous(true)
let hbox1 = newBox(Orientation.horizontal, 10)
hbox1.setHomogeneous(true)
let hbox2 = newBox(Orientation.horizontal, 1)
hbox2.setHomogeneous(false)
let label = newLabel("Value:")
let entry = newEntry()
entry.setText("0")
let btnQuit = newButton("Quit")
let btnIncr = newButton("Increment")
let btnDecr = newButton("Decrement")
 
hbox2.add(label)
hbox2.add(entry)
hbox1.add(btnIncr)
hbox1.add(btnDecr)
 
content.packStart(hbox2, true, true, 0)
content.packStart(hbox1, true, true, 0)
content.packStart(btnQuit, true, true, 0)
 
window.setBorderWidth(5)
window.add(content)
 
let context = Context(value: 0, entry: entry, btnIncr: btnIncr, btnDecr: btnDecr)
 
discard btnQuit.connect("clicked", onQuit, window)
discard btnIncr.connect("clicked", onIncr, context)
discard btnDecr.connect("clicked", onDecr, context)
discard entry.connect("changed", onEntryChange, context)
 
context.checkButtons()
window.showAll()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
let app = newApplication(Application, "Rosetta.GuiControls")
discard app.connect("activate", activate)
discard app.run()</syntaxhighlight>
 
===Using IUP===
{{libheader|IUP}}
<syntaxhighlight lang="nim">import
iup, strutils, math
 
Line 1,567 ⟶ 2,184:
discard dlg.show()
discard mainloop()
iup.close()</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
Extremely basic implementation using the GTK library.
<lang perl6>use GTK::Simple;
my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );
$app.set_content(
my $box = GTK::Simple::HBox.new(
my $inc = GTK::Simple::Button.new( label => ' + ' ),
my $value = GTK::Simple::Entry.new,
my $dec = GTK::Simple::Button.new( label => ' - ' )
)
);
 
use strict;
$app.border_width = 10;
use warnings;
$box.spacing = 10;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
 
my $value.changed.tap: {= 0;
$value.text.=subst(/\D/, '');
$inc.sensitive = $value.text < 10;
$dec.sensitive = $value.text > 0;
}
$value.text = 0;
$inc.clicked.tap: { $value.text += 1 }
$dec.clicked.tap: { $value.text -= 1 }
$app.run;</lang>
 
my $mw = MainWindow->new;
=={{header|Phix}}==
$mw->title( 'GUI component enable/disable' );
Note: this validates each input char separately, and '-' is not "NUMBER": the only way to get numbers <0 or >9 into the input field is to paste them.
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
<lang Phix>include pGUI.e
my $entry = $lf->Entry( -width => 10, -textvariable => \$value,
-validate => 'key', -validatecommand => sub {
$_[0] =~ /^\d{1,9}\z/ ? do{setenable($_[0]); 1} : 0
},
)->pack(-fill => 'x', -expand => 1);
my $inc = $mw->Button( -text => 'increment',
-command => sub { $value++; setenable($value) },
)->pack( -side => 'left' );
my $dec = $mw->Button( -text => 'decrement',
-command => sub { $value--; setenable($value) },
)->pack( -side => 'right' );
 
setenable($value);
Ihandle txt, inc, dec, hbx, vbx, dlg
 
MainLoop;
function activate(integer v)
IupSetInt(txt,"VALUE",v)
IupSetAttribute(inc,"ACTIVE",iff(v<10,"YES":"NO"))
IupSetAttribute(dec,"ACTIVE",iff(v>0,"YES":"NO"))
IupSetAttribute(txt,"ACTIVE",iff(v=0,"YES":"NO"))
return IUP_CONTINUE
end function
 
sub setenable
function valuechanged_cb(Ihandle /*ih*/)
{
return activate(IupGetInt(txt,"VALUE"))
$inc and $inc->configure( -state => $_[0] < 10 ? 'normal' : 'disabled' );
end function
$dec and $dec->configure( -state => $_[0] > 0 ? 'normal' : 'disabled' );
$entry and $entry->configure( -state => $_[0] == 0 ? 'normal' : 'disabled' );
}</syntaxhighlight>
 
=={{header|Phix}}==
function inc_cb(Ihandle /*ih*/)
Note: this validates each input char separately, and '-' is not "NUMBER": the only way to get numbers <0 or >9 into the input field is to paste them.
return activate(IupGetInt(txt,"VALUE")+1)
{{libheader|Phix/basics}}
end function
{{libheader|Phix/pGUI}}
 
<!--<syntaxhighlight lang="phix">-->
function dec_cb(Ihandle /*ih*/)
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
return activate(IupGetInt(txt,"VALUE")-1)
end function
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">inc</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dec</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hbx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">vbx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
 
function esc_close(Ihandle /*ih*/, atom c)
<span style="color: #008080;">function</span> <span style="color: #000000;">activate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
return iff(c=K_ESC?IUP_CLOSE:IUP_CONTINUE)
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inc</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;"><</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YES"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"NO"</span><span style="color: #0000FF;">))</span>
 
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dec</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YES"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"NO"</span><span style="color: #0000FF;">))</span>
IupOpen("../pGUI/")
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YES"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"NO"</span><span style="color: #0000FF;">))</span>
txt = IupText("VALUECHANGED_CB",Icallback("valuechanged_cb"),"FILTER=NUMBER, EXPAND=YES")
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
inc = IupButton("increment",Icallback("inc_cb"))
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
dec = IupButton("decrement",Icallback("dec_cb"),"ACTIVE=NO")
hbx = IupHbox({inc,dec},"MARGIN=0x10, GAP=20")
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
vbx = IupVbox({txt,hbx},"MARGIN=40x20")
<span style="color: #008080;">return</span> <span style="color: #000000;">activate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">))</span>
dlg = IupDialog(vbx)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
IupShow(dlg)
<span style="color: #008080;">function</span> <span style="color: #000000;">inc_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
IupMainLoop()
<span style="color: #008080;">return</span> <span style="color: #000000;">activate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
IupClose()</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">dec_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">activate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">esc_close</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span><span style="color: #0000FF;">?</span><span style="color: #004600;">IUP_CLOSE</span><span style="color: #0000FF;">:</span><span style="color: #004600;">IUP_CONTINUE</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;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"FILTER=NUMBER, EXPAND=YES"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">inc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"increment"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"inc_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">dec</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"decrement"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"dec_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"ACTIVE=NO"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">hbx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">inc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dec</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=0x10, GAP=20"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">vbx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hbx</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"MARGIN=40x20"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vbx</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"K_ANY"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"esc_close"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
The standard PicoLisp GUI is HTTP based. Connect your browser to
http://localhost:8080 after starting the following script.
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
Line 1,660 ⟶ 2,290:
 
(server 8080 "!start")
(wait)</langsyntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<langsyntaxhighlight Prologlang="prolog">dialog('GUI_Interaction',
[ object :=
GUI_Interaction,
Line 1,763 ⟶ 2,393:
-> send(Incr, active, @off)).
 
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Enumeration
#TextGadget
#AddButton
Line 1,811 ⟶ 2,441:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
#!/usr/bin/env python3
 
import tkinter as tk
 
class MyForm(tk.Frame):
 
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack(expand=True, fill="both", padx=10, pady=10)
self.master.title("Controls")
self.setupUI()
 
def setupUI(self):
self.value_entry = tk.Entry(self, justify=tk.CENTER)
self.value_entry.grid(row=0, column=0, columnspan=2,
padx=5, pady=5, sticky="nesw")
self.value_entry.insert('end', '0')
self.value_entry.bind("<KeyPress-Return>", self.eventHandler)
 
self.decre_btn = tk.Button(self, text="Decrement", state=tk.DISABLED)
self.decre_btn.grid(row=1, column=0, padx=5, pady=5)
self.decre_btn.bind("<Button-1>", self.eventHandler)
 
self.incre_btn = tk.Button(self, text="Increment")
self.incre_btn.grid(row=1, column=1, padx=5, pady=5)
self.incre_btn.bind("<Button-1>", self.eventHandler)
 
def eventHandler(self, event):
value = int(self.value_entry.get())
if event.widget == self.value_entry:
if value > 10:
self.value_entry.delete("0", "end")
self.value_entry.insert("end", "0")
elif value == 10:
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.DISABLED)
self.decre_btn.config(state=tk.NORMAL)
elif value == 0:
self.value_entry.config(state=tk.NORMAL)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.DISABLED)
elif (value > 0) and (value < 10):
self.value_entry.config(state=tk.DISABLED)
self.incre_btn.config(state=tk.NORMAL)
self.decre_btn.config(state=tk.NORMAL)
else:
if event.widget == self.incre_btn:
if (value >= 0) and (value < 10):
value += 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete("0", "end")
self.value_entry.insert("end", str(value))
if value > 0:
self.decre_btn.config(state=tk.NORMAL)
self.value_entry.config(state=tk.DISABLED)
if value == 10:
self.incre_btn.config(state=tk.DISABLED)
elif event.widget == self.decre_btn:
if (value > 0) and (value <= 10):
value -= 1
self.value_entry.config(state=tk.NORMAL)
self.value_entry.delete("0", "end")
self.value_entry.insert("end", str(value))
self.value_entry.config(state=tk.DISABLED)
if (value) < 10:
self.incre_btn.config(state=tk.NORMAL)
if (value) == 0:
self.decre_btn.config(state=tk.DISABLED)
self.value_entry.config(state=tk.NORMAL)
 
def main():
app = MyForm()
app.mainloop()
 
if __name__ == "__main__":
main()
</syntaxhighlight>
 
Result: [https://ibb.co/cEmqy5]
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
Line 1,841 ⟶ 2,553:
addHandlerChanged(down_btn, handler=rement, action=-1)
addHandlerChanged(up_btn, handler=rement, action=1)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket/gui
Line 1,871 ⟶ 2,583:
 
(send frame show #t)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Extremely basic implementation using the GTK library.
<syntaxhighlight lang="raku" line>use GTK::Simple;
use GTK::Simple::App;
 
my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );
 
$app.set-content(
my $box = GTK::Simple::HBox.new(
my $inc = GTK::Simple::Button.new( label => ' + ' ),
my $value = GTK::Simple::Entry.new,
my $dec = GTK::Simple::Button.new( label => ' - ' )
)
);
 
$app.border-width = 10;
$box.spacing = 10;
 
$value.changed.tap: {
$value.text.=subst(/\D/, '');
$inc.sensitive = $value.text < 10;
$dec.sensitive = $value.text > 0;
}
 
$value.text = '0';
 
$inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str }
$dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str }
 
$app.run;</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red[]
 
enable: does [
f/enabled?: 0 = n
i/enabled?: 10 > n
d/enabled?: 0 < n
]
 
view [
f: field "0" [either error? try [n: to-integer f/text] [f/text: "0"] [enable]]
i: button "increment" [f/text: mold n: add to-integer f/text 1 enable]
d: button "decrement" disabled [f/text: mold n: subtract to-integer f/text 1 enable]
]</syntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Load "guilib.ring"
 
Line 1,910 ⟶ 2,669:
lineedit1.settext(num)
if number(num)<0 btn2.setDisabled(True) ok
</syntaxhighlight>
</lang>
Output:
[[File:CalmoSoftGui.jpg]]
Line 1,916 ⟶ 2,675:
=={{header|Ruby}}==
{{libheader|Shoes}}
<langsyntaxhighlight lang="ruby">Shoes.app do
@number = edit_line
@number.change {update_controls}
Line 1,930 ⟶ 2,689:
 
update_controls 0
end</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField }
import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }
 
Line 1,982 ⟶ 2,741:
centerOnScreen()
} // def top(
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|top input vh incButton decButton|
 
vh := ValueHolder with:0.
Line 2,005 ⟶ 2,764:
decButton enableChannel:(BlockValue with:[:v | v > 0] argument:vh).
 
top open</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
# Model
Line 2,039 ⟶ 2,798:
.dec state [expr {$field > 0 ? "!disabled" : "disabled"}]
}
updateEnables; # Force initial state of buttons</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gtk+-3.0}}
 
<syntaxhighlight lang="vala">bool validate_input(Gtk.Window window, string str){
int64 val;
bool ret = int64.try_parse(str,out val);;
 
if(!ret || str == ""){
var dialog = new Gtk.MessageDialog(window,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
"Invalid value");
dialog.run();
dialog.destroy();
}
if(str == ""){
ret = false;
}
 
return ret;
}
 
int main (string[] args) {
Gtk.init (ref args);
 
var window = new Gtk.Window();
window.title = "Rosetta Code";
window.window_position = Gtk.WindowPosition.CENTER;
window.destroy.connect(Gtk.main_quit);
window.set_default_size(0,0);
 
var box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 1);
box.set_border_width(1);
 
var label = new Gtk.Label("Value:");
var entry = new Gtk.Entry();
var ib = new Gtk.Button.with_label("inc");
var db = new Gtk.Button.with_label("dec");
 
ib.set_sensitive(true); //enable the inc button
db.set_sensitive(false); //disable the dec button
 
entry.set_text("0"); //initialize to zero
 
entry.activate.connect(() => {
var str = entry.get_text();
 
if(!validate_input(window, str)){
entry.set_text("0"); //initialize to zero on wrong input
}else{
int num = int.parse(str);
if(num != 0){
entry.set_sensitive(false); //disable the field
}
if(num > 0 && num < 10){
ib.set_sensitive(true); //enable the inc button
db.set_sensitive(true); //enable the dec button
}
if(num > 9){
ib.set_sensitive(false); //disable the inc button
db.set_sensitive(true); //enable the dec button
}
}
});
 
ib.clicked.connect(() => {
// read and validate the entered value
if(!validate_input(window, entry.get_text())){
entry.set_text("0"); //initialize to zero on wrong input
}else{
int num = int.parse(entry.get_text()) + 1;
entry.set_text(num.to_string());
if(num > 9){
ib.set_sensitive(false); //disable the inc button
}
if(num != 0){
db.set_sensitive(true); //enable the dec button
entry.set_sensitive(false); //disable the field
}
if(num == 0){
entry.set_sensitive(true); //enable the field
}
if(num < 0){
db.set_sensitive(false); //disable the dec button
}
}
});
 
db.clicked.connect(() => {
// read and validate the entered value
int num = int.parse(entry.get_text()) - 1;
entry.set_text(num.to_string());
if(num == 0){
db.set_sensitive(false); //disable the dec button
entry.set_sensitive(true); //enable the field
}
if(num < 10){
ib.set_sensitive(true); //enable the inc button
}
});
 
box.pack_start(label, false, false, 2);
box.pack_start(entry, false, false, 2);
box.pack_start(ib, false, false, 2);
box.pack_start(db, false, false, 2);
 
window.add(box);
 
window.show_all();
 
Gtk.main();
return 0;
}
</syntaxhighlight>
 
=={{header|Visual Basic}}==
Line 2,051 ⟶ 2,924:
by a "spinner" or "up-down" control, not by buttons.)
 
<langsyntaxhighlight lang="vb">VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
Line 2,121 ⟶ 2,994:
cmdDec.Enabled = True
End Select
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
Graphical
 
Notes:
 
1) "v install ui" to get, also to locally check source and examples.
 
2) For alternative UI toolkits, check github.com/vlang/awesome-v (Awesome V).
 
<syntaxhighlight lang="Zig">
import ui
import gx
 
const (
win_width = 400
win_height = 40
)
 
[heap]
struct App {
mut:
window &ui.Window = unsafe {nil}
counter string = "0"
}
 
fn main() {
mut app := &App{}
app.window = ui.window(
width: win_width
height: win_height
title: "Counter"
mode: .resizable
layout: ui.row(
spacing: 5
margin_: 10
widths: ui.stretch
heights: ui.stretch
children: [
ui.textbox(
max_len: 20
read_only: false
is_numeric: true
text: &app.counter
),
ui.button(
text: "increment"
bg_color: gx.light_gray
radius: 5
border_color: gx.gray
on_click: app.btn_click_inc
),
ui.button(
text: "decrement"
bg_color: gx.light_gray
radius: 5
border_color: gx.gray
on_click: app.btn_click_dec
),
]
)
)
ui.run(app.window)
}
 
fn (mut app App) btn_click_inc(mut btn ui.Button) {
if app.counter.int() > 10 {
btn.disabled = true
return
}
app.counter = (app.counter.int() + 1).str()
}
 
fn (mut app App) btn_click_dec(mut btn ui.Button) {
if app.counter.int() < 0 {
btn.disabled = true
return
}
app.counter = (app.counter.int() - 1).str()
}
</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
{{libheader|Wren-polygon}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, Color
import "input" for Mouse, Keyboard
import "dome" for Window
import "./polygon" for Polygon
 
class Button {
construct new(x, y, w, h, legend, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_legend = legend
_c = c
_oc = oc
_lc = lc
_enabled = true
}
 
enabled { _enabled }
enabled=(e) { _enabled = e }
 
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_legend)
var lx = ((_w - l.x)/2).truncate
lx = (lx > 0) ? _x + lx : _x + 1
var ly = ((_h - l.y)/2).truncate
ly = (ly > 0) ? _y + ly : _y + 1
var col = _enabled ? _lc : Color.darkgray
Canvas.print(_legend, lx, ly, col)
}
 
justClicked { Mouse["left"].justPressed && _rect.contains(Mouse.position.x, Mouse.position.y) }
}
 
class TextBox {
construct new(x, y, w, h, label, c, oc, lc) {
var vertices = [[x, y], [x+w, y], [x+w, y+h], [x, y+h]]
_rect = Polygon.quick(vertices)
_x = x
_y = y
_w = w
_h = h
_label = label
_c = c
_oc = oc
_lc = lc
_text = ""
_enabled = true
}
 
text { _text }
text=(t) { _text = t }
 
enabled { _enabled }
enabled=(e) { _enabled = e }
 
draw() {
_rect.drawfill(_c)
_rect.draw(_oc)
var l = Canvas.getPrintArea(_label).x
var lx = _x - l - 7
if (lx < 1) {
lx = 1
_label = _label[0..._x]
}
var col = _enabled ? _lc : Color.darkgray
Canvas.print(_label, lx, _y, col)
Canvas.getPrintArea(_label).x
Canvas.print(_text, _x + 3, _y + 1, Color.black)
}
}
 
class GUIControlEnablement {
construct new() {
Window.title = "GUI control enablement"
_btnIncrement = Button.new(60, 40, 80, 80, "Increment", Color.red, Color.blue, Color.white)
_btnDecrement = Button.new(180, 40, 80, 80, "Decrement", Color.green, Color.blue, Color.white)
_txtValue = TextBox.new(140, 160, 80, 8, "Value", Color.white, Color.blue, Color.white)
_txtValue.text = "0"
Keyboard.handleText = true
}
 
init() {
_btnDecrement.enabled = false
drawControls()
}
 
update() {
if (_btnIncrement.enabled && _btnIncrement.justClicked) {
var number = Num.fromString(_txtValue.text) + 1
_btnIncrement.enabled = (number < 10)
_btnDecrement.enabled = true
_txtValue.enabled = (number == 0)
_txtValue.text = number.toString
} else if (_btnDecrement.enabled && _btnDecrement.justClicked) {
var number = Num.fromString(_txtValue.text) - 1
_btnDecrement.enabled = (number > 0)
_btnIncrement.enabled = true
_txtValue.enabled = (number == 0)
_txtValue.text = number.toString
} else if (_txtValue.enabled && "0123456789".any { |d| Keyboard[d].justPressed }) {
_txtValue.text = Keyboard.text
_txtValue.enabled = (_txtValue.text == "0")
_btnIncrement.enabled = true
_btnDecrement.enabled = (_txtValue.text != "0")
}
}
 
draw(alpha) {
drawControls()
}
 
drawControls() {
Canvas.cls()
_btnIncrement.draw()
_btnDecrement.draw()
_txtValue.draw()
}
}
 
var Game = GUIControlEnablement.new()</syntaxhighlight>
9,476

edits