GUI enabling/disabling of controls: Difference between revisions
GUI enabling/disabling of controls (view source)
Revision as of 10:25, 9 December 2023
, 6 months ago→{{header|Wren}}: Changed to Wren S/H
No edit summary |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(36 intermediate revisions by 17 users not shown) | |||
Line 2:
{{omit from|ACL2}}
{{omit from|Applesoft BASIC|no concept of a GUI}}
{{omit from|AWK|no concept of a GUI}}
{{omit from|Batch File}}
{{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 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 51 ⟶ 52:
disabling.adb:
<
with Gtk.Main;
with Gtk.Handlers;
Line 219 ⟶ 220:
Gtk.Main.Main;
end Disabling;</
=={{header|AutoHotkey}}==
<
GUI, Add, button,, Increment
GUI, Add, button, xp+70 yp, Decrement ; xp+70 and yp are merely positioning options
Line 266 ⟶ 267:
GuiClose:
ExitApp
; Ensures the script ends when the GUI is closed.</
=={{header|
==={{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}}
<
INSTALL @lib$+"WINLIB5"
ES_NUMBER = 8192
Line 306 ⟶ 345:
SYS "GetDlgItemInt", !form%, 101, 0, 1 TO number%
SYS "SetDlgItemInt", !form%, 101, number% - 1, 1
ENDPROC</
{{out}}
<p>
Line 316 ⟶ 355:
<pre>file main.c</pre>
<
#include "resource.h"
Line 395 ⟶ 434:
EnableWindow( GetDlgItem(hwnd,IDC_INCREMENT), n<MAX_VALUE );
EnableWindow( GetDlgItem(hwnd,IDC_DECREMENT), n>MIN_VALUE );
}</
<pre>file resource.h</pre>
<
#define IDC_INPUT 1001
#define IDC_INCREMENT 1002
#define IDC_DECREMENT 1003
#define IDC_QUIT 1004</
<pre>file resource.rc</pre>
<
#include "resource.h"
Line 420 ⟶ 459:
PUSHBUTTON "Quit", IDC_QUIT, 117, 25, 30, 14
RTEXT "Value:", -1, 10, 8, 20, 8
}</
=={{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>
<
#define TASK_H
Line 454 ⟶ 578:
QHBoxLayout *lowerPart ;
} ;
#endif</
<pre>file task.cpp</pre>
<
#include <QString>
#include "task.h"
Line 510 ⟶ 634:
number-- ;
entryField->setText( QString("%1").arg( number )) ;
}</
<pre>main.cpp</pre>
<
#include "task.h"
Line 521 ⟶ 645:
theWidget.show( ) ;
return app.exec( ) ;
}</
=={{header|Delphi}}==
<
TForm1 = class(TForm)
MaskEditValue: TMaskEdit; // Set Editmask on: "99;0; "
Line 639 ⟶ 678:
begin
MaskEditValue.Text := IntToStr(Succ(StrToIntDef(Trim(MaskEditValue.Text), 0)));
end;</
=={{header|Fantom}}==
<
using gfx
Line 709 ⟶ 749:
}.open
}
}</
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#Include "windows.bi"
Line 750 ⟶ 790:
End
</syntaxhighlight>
=={{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 756 ⟶ 1,091:
This uses the Unicon specific graphics library.
<syntaxhighlight lang="unicon">
import gui
$include "guih.icn"
Line 844 ⟶ 1,179:
w.show_modal ()
end
</syntaxhighlight>
=={{header|J}}==
'''J 8.x'''
<
pc task nosize;
cc decrement button;cn "Decrement";
Line 873 ⟶ 1,208:
task_decrement_button=:verb define
update Value=: ": _1 + 0 ". Value
)</
'''J 6.x'''
<
pc task nosize;
xywh 6 30 48 12;cc decrement button;cn "-";
Line 899 ⟶ 1,234:
task_decrement_button=:verb define
update Value=: ": _1 + 0 ". Value
)</
Example use:
<syntaxhighlight lang="text"> task_run''</
=={{header|Java}}==
{{works with|Swing}}
{{works with|AWT}}
<
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Line 1,060 ⟶ 1,395:
new Interact().setVisible(true);
}
}</
{{libheader|JavaFX}}
{{works with|Java|8}}
<
import javafx.application.Application;
import javafx.beans.property.LongProperty;
Line 1,121 ⟶ 1,456:
increment.setOnAction(event-> inputValue.set(inputValue.get() + 1));
// incr-button is disabled when input is >=
increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10));
Line 1,144 ⟶ 1,479:
}
}
</syntaxhighlight>
=={{header|Julia}}==
<
using Tk
w = Toplevel("GUI enabling/disabling")
Line 1,197 ⟶ 1,532:
</syntaxhighlight>
=={{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}}==
<
textbox #demo.val, 20, 50, 90, 24
button #demo.dec, "Decrement", [btnDecrement], UL, 20, 90, 90, 24
Line 1,279 ⟶ 1,688:
#demo.val "!disable"
end if
End Sub</
=={{header|LiveCode}}==
Line 1,295 ⟶ 1,704:
4. Select Object->Card Script and enter the following to handle enabling the buttons.
<
switch
case v <= 0
Line 1,312 ⟶ 1,721:
put v into fld "Field1"
end switch
end enableButtons</
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<
put field "Field1" into x
add 1 to x
enableButtons x
end mouseUp</
Repeat for Button 2 (note we are subtracting here)<
put field "Field1" into x
subtract 1 from x
enableButtons x
end mouseUp</
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.<
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,334 ⟶ 1,743:
pass rawKeyDown
end if
end rawKeyDown</
Switch back to the form, and enter run mode to execute.
Line 1,340 ⟶ 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|
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.
<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]]}]</
=={{header|NewLISP}}==
<
; url: http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
; author: oofoe 2012-02-02
Line 1,395 ⟶ 1,925:
(gs:listen)
(exit)</
Screenshot:
Line 1,402 ⟶ 1,932:
=={{header|Nim}}==
===
{{libheader|Gtk2}}
<syntaxhighlight lang="nim">import gtk2, strutils, glib2
var valu: int = 0
proc thisDestroy(widget: PWidget, data: Pgpointer){.cdecl.} =
main_quit()
nim_init()
var window = window_new(gtk2.WINDOW_TOPLEVEL)
var content = vbox_new(
var hbox1 = hbox_new(
var entry_fld = entry_new()
entry_fld.set_text("0")
Line 1,425 ⟶ 1,952:
add(hbox1,btn_inc)
add(hbox1,btn_dec)
pack_start(content, entry_fld,
pack_start(content, hbox1,
pack_start(content, btn_quit,
set_border_width(
add(window, content)
proc thisCheckBtns =
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:
dec(valu)
entry_fld.set_text($valu)
thisCheckBtns()
proc thisTextChanged(widget:
try:
valu = parseInt($entry_fld.get_text())
except
entry_fld.set_text($valu
thisCheckBtns()
discard signal_connect(window, "destroy",
SIGNAL_FUNC(thisDestroy), nil)
Line 1,465 ⟶ 1,988:
discard signal_connect(btn_dec, "clicked",
SIGNAL_FUNC(thisDec), nil)
SIGNAL_FUNC(thisTextChanged), nil)
show_all(window)
thisCheckBtns()
main()</
===Using Gtk3 (gintro)===
{{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,564 ⟶ 2,184:
discard dlg.show()
discard mainloop()
iup.close()</
=={{header|Perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use Tk::Dialog;
use Tk::LabFrame;
my $value
my $mw = MainWindow->new;
$mw->title( 'GUI component enable/disable' );
my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1);
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);
MainLoop;
sub setenable
{
$inc and $inc->configure( -state => $_[0] < 10 ? 'normal' : 'disabled' );
$dec and $dec->configure( -state => $_[0] > 0 ? 'normal' : 'disabled' );
$entry and $entry->configure( -state => $_[0] == 0 ? 'normal' : 'disabled' );
}</syntaxhighlight>
=={{header|Phix}}==
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.
{{libheader|Phix/basics}}
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">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>
<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>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #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>
<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>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">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>
<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: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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;">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.
<
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
Line 1,657 ⟶ 2,290:
(server 8080 "!start")
(wait)</
=={{header|Prolog}}==
Works with SWI-Prolog and XPCE.
<
[ object :=
GUI_Interaction,
Line 1,760 ⟶ 2,393:
-> send(Incr, active, @off)).
</syntaxhighlight>
=={{header|PureBasic}}==
<
#TextGadget
#AddButton
Line 1,808 ⟶ 2,441:
EndIf
Until Event=#PB_Event_CloseWindow
EndIf</
=={{header|Python}}==
<syntaxhighlight lang="python">
#!/usr/bin/env python3
Line 1,918 ⟶ 2,521:
if __name__ == "__main__":
main()
</syntaxhighlight>
Result: [https://ibb.co/cEmqy5]
=={{header|R}}==
<syntaxhighlight lang="r">
library(gWidgets)
options(guiToolkit="RGtk2") ## using gWidgtsRGtk2
w <- gwindow("Disable components")
g <- ggroup(cont=w, horizontal=FALSE)
e <- gedit("0", cont=g, coerce.with=as.numeric)
bg <- ggroup(cont=g)
down_btn <- gbutton("-", cont=bg)
up_btn <- gbutton("+", cont=bg)
update_ctrls <- function(h,...) {
val <- svalue(e)
enabled(down_btn) <- val >= 0
enabled(up_btn) <- val <= 10
}
rement <- function(h,...) {
svalue(e) <- svalue(e) + h$action
update_ctrls(h,...)
}
addHandlerChanged(e, handler=update_ctrls)
addHandlerChanged(down_btn, handler=rement, action=-1)
addHandlerChanged(up_btn, handler=rement, action=1)
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket/gui
Line 1,950 ⟶ 2,583:
(send frame show #t)
</syntaxhighlight>
=={{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}}==
<
Load "guilib.ring"
Line 1,989 ⟶ 2,669:
lineedit1.settext(num)
if number(num)<0 btn2.setDisabled(True) ok
</syntaxhighlight>
Output:
[[File:CalmoSoftGui.jpg]]
Line 1,995 ⟶ 2,675:
=={{header|Ruby}}==
{{libheader|Shoes}}
<
@number = edit_line
@number.change {update_controls}
Line 2,009 ⟶ 2,689:
update_controls 0
end</
=={{header|Scala}}==
<
import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped }
Line 2,061 ⟶ 2,741:
centerOnScreen()
} // def top(
}</
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<
vh := ValueHolder with:0.
Line 2,084 ⟶ 2,764:
decButton enableChannel:(BlockValue with:[:v | v > 0] argument:vh).
top open</
=={{header|Tcl}}==
{{libheader|Tk}}
<
# Model
Line 2,118 ⟶ 2,798:
.dec state [expr {$field > 0 ? "!disabled" : "disabled"}]
}
updateEnables; # Force initial state of buttons</
=={{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,130 ⟶ 2,924:
by a "spinner" or "up-down" control, not by buttons.)
<
Begin VB.Form Form1
Caption = "Form1"
Line 2,200 ⟶ 2,994:
cmdDec.Enabled = True
End Select
End Sub</
=={{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>
|