Simple windowed application
You are encouraged to solve this task according to the task description, using any language you may know.
This task asks to create a window with a label that says "There have been no clicks yet" and a button that says "click me". Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
Ada
The following solution is based on bindings to GTK+. Ada as a language does not provide standard GUI. Apart from GtkAda, there exist numerous other GUI bindings and libraries: CLAW, AdaGLUT, GWindow, JEWL, win32ada, QtAda etc. <lang ada> with Gdk.Event; use Gdk.Event; with Gtk.Button; use Gtk.Button; with Gtk.Label; use Gtk.Label; with Gtk.Window; use Gtk.Window; with Gtk.Widget; use Gtk.Widget; with Gtk.Table; use Gtk.Table;
with Gtk.Handlers; with Gtk.Main;
procedure Simple_Windowed_Application is
Window : Gtk_Window; Grid : Gtk_Table; Button : Gtk_Button; Label : Gtk_Label; Count : Natural := 0;
package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); package Return_Handlers is new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
function Delete_Event (Widget : access Gtk_Widget_Record'Class) return Boolean is begin return False; end Delete_Event;
procedure Destroy (Widget : access Gtk_Widget_Record'Class) is begin Gtk.Main.Main_Quit; end Destroy;
procedure Clicked (Widget : access Gtk_Widget_Record'Class) is begin Count := Count + 1; Set_Text (Label, "The button clicks:" & Natural'Image (Count)); end Clicked;
begin
Gtk.Main.Init; Gtk.Window.Gtk_New (Window); Gtk_New (Grid, 1, 2, False); Add (Window, Grid); Gtk_New (Label, "There have been no clicks yet"); Attach (Grid, Label, 0, 1, 0, 1); Gtk_New (Button, "Click me"); Attach (Grid, Button, 0, 1, 1, 2); Return_Handlers.Connect ( Window, "delete_event", Return_Handlers.To_Marshaller (Delete_Event'Access) ); Handlers.Connect ( Window, "destroy", Handlers.To_Marshaller (Destroy'Access) ); Handlers.Connect ( Button, "clicked", Handlers.To_Marshaller (Clicked'Access) ); Show_All (Grid); Show (Window);
Gtk.Main.Main;
end Simple_Windowed_Application; </lang>
AutoHotkey
<lang Autohotkey>Gui, Add, Text, vGuiText, There have been no clicks yet ; add a Text-Control Gui, Add, Button, gClickButton xm, click me ; add a Button-Control Gui, Show ; show the Window return ; end of the autoexection section
ClickButton: ; the subroutine executed each time the Button-Control is clicked count ++ ; increment the click-counting var GuiControl, , GuiText , %count% ; update the Text-Control with the click-counting var return ; end of the subroutine
- exit process when window is closed
GuiClose: ; the subroutine executed when the Window is closed ExitApp ; exit this process</lang>
C
<lang c>#include <stdio.h>
- include <gtk/gtk.h>
const gchar *clickme = "Click Me"; guint counter = 0;
- define MAXLEN 64
void clickedme(GtkButton *o, gpointer d) {
GtkLabel *l = GTK_LABEL(d); char nt[MAXLEN]; counter++; snprintf(nt, MAXLEN, "You clicked me %d times", counter); gtk_label_set_text(l, nt);
}
int main(int argc, char **argv) {
GtkWindow *win; GtkButton *button; GtkLabel *label; GtkVBox *vbox; gtk_init(&argc, &argv); win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, clickme); button = (GtkButton*)gtk_button_new_with_label(clickme); label = (GtkLabel*)gtk_label_new("There have been no clicks yet"); gtk_label_set_single_line_mode(label, TRUE); vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0;
}</lang>
C#
<lang csharp> using System.Windows.Forms;
namespace RosettaCode.SimpleWindowedApplication {
public class RosettaForm:Form { private Label label = new Label(); private Button button = new Button(); private int clickCount = 0;
public RosettaForm() { label.Text = "There have been no clicks yet."; label.AutoSize = true; button.Text = "Click me."; button.Dock = DockStyle.Bottom; button.AutoSize = true; button.Click += delegate { clickCount++; label.Text = "Clicks so far: " + clickCount; };
Controls.Add(label); Controls.Add(button); } }
class Program { static void Main() { Application.Run(new RosettaForm()); } }
} </lang>
Common Lisp
<lang lisp>(defpackage #:rcswa
(:use #:clim #:clim-lisp))
(in-package #:rcswa)</lang>
This version uses CLIM's command system:
<lang lisp>(define-application-frame simple-windowed-application ()
((clicks :initform 0 :accessor clicks-of)) (:menu-bar t) (:pane (make-pane 'application-pane :width '(40 :character) :height '(3 :character) :display-time :command-loop :display-function (lambda (pane stream) (declare (ignore pane)) (format stream "~[There have been no clicks yet.~ ~:;~:*There ~[have~;has~:;have~]~:* been ~R click~:P.~]" (clicks-of *application-frame*))))))
(define-simple-windowed-application-command (com-click-me :menu t)
() (incf (clicks-of *application-frame*)))</lang>
This version uses an explicit pushbutton gadget, and may be used if more direct control over the UI layout and behavior is needed:
<lang lisp>(define-application-frame simple-windowed-application ()
((clicks :initform 0 :accessor clicks-of)) (:panes (the-label :application :width '(40 :character) :height '(3 :character) :display-time t :display-function (lambda (pane stream) (declare (ignore pane)) (format stream "~[There have been no clicks yet.~ ~:;~:*There ~[have~;has~:;have~]~:* been ~R click~:P.~]" (clicks-of *application-frame*)))) (the-button :push-button :label "Click Me" :activate-callback (lambda (button) (declare (ignore button)) (incf (clicks-of *application-frame*)) (redisplay-frame-pane *application-frame* (find-pane-named *application-frame* 'the-label) :force-p t)))) (:layouts (default (vertically (:equalize-width nil :align-x :center) the-label (spacing (:thickness 10) the-button)))))</lang>
In either case, the window is opened with:
<lang lisp>(run-frame-top-level (make-application-frame 'simple-windowed-application))</lang>
D
DFL
<lang d>module winapp ; import dfl.all ; import std.string ;
class MainForm: Form {
Label label ; Button button ; this() { width = 240 ; with(label = new Label) { text = "There have been no clicks yet" ; dock = DockStyle.TOP ; parent = this ; } with(button = new Button) { dock = DockStyle.BOTTOM ; text = "Click Me" ; parent = this ; click ~= &onClickButton ; } height = label.height + button.height + 36 ; } private void onClickButton(Object sender, EventArgs ea) { static int count = 0 ; label.text = "You had been clicked me " ~ std.string.toString(++count) ~ " times." ; }
}
void main() {
Application.run(new MainForm);
}</lang>
Hybrid
Hybrid uses config files to describe GUI layout. SimpleWindow.cfg:
import "themes/default.cfg" new FramedTopLevelWindow main { frame.text = "Simple Window"; new Label label { text = "There have been no clicks yet"; } new Button button { text = "Click me"; size = 201 20; } }
SimpleWindow.d: <lang d>module SimpleWindow; import tango.text.convert.Integer; import tango.core.Thread; // For Thread.yield
import xf.hybrid.Hybrid; //For widgets and general API import xf.hybrid.backend.GL; // For OpenGL Renderer
void main() { //load config file scope cfg = loadHybridConfig(`./SimpleWindow.cfg`); scope renderer = new Renderer; auto counter = 0;
bool programRunning = true; while (programRunning) { // Tell Hybrid what config to use gui.begin(cfg); // Exit program if user clicks the Close button if (gui().getProperty!(bool)("main.frame.closeClicked")) { programRunning = false; } // Update text on the label if (counter != 0) Label("main.label").text = toString(counter); // Increment counter if the button has been clicked if (Button("main.button").clicked) { counter++; } // Finalize. Prepare to render gui.end(); // Render window using OpenGL Renderer gui.render(renderer);
Thread.yield(); } }</lang>
Delphi
Creating a "basic windowed application" in Delphi is quite simple. Start up the IDE and the default application is a single windowed app. This will have two files, the main project file "project1" and a unit file, "unit1". What I a going to do here is going to be somewhat different. I will do it all dynamically from the main "program file". Create this in any text editor and you can then either open it in the IDE to build it, or invoke the command line compiler. There is quite a bit going on behind the scenes with the VCL and the RTL.
Filename = SingleWinApp.dpr
NOTE: The project name here must match the name of the file.
<lang delphi> -- begin file --
Program SingleWinApp ; // This is the equivalent of the C #include Uses Forms, Windows, Messages, Classes, Graphics, Controls, StdCtrls ;
type // The only reason for this declaration is to allow the connection of the // on click method to the forms button object. This class declaration adds // a procedure.
TMainForm class(tform) Procedure AddClicks(sender : tObject); end;
// Use these globals. var MainForm : tForm ; aLabel : tLabel ; aButton : tButton ; i : integer = 0 ;
// This is the Method call that we connect to the button object // to start counting the clicks. Procedure tMainForm.AddClicks(sender :tObject) begin inc(i); aLabel.Caption := IntToStr(i) + ' Clicks since startup' ; end;
Begin // Do all the behind the scenes stuff that sets up the Windows environment Application.Initialize ;
// Create the form // Forms can either be created with an owner, like I have done here, or with // the owner set to Nil. In pascal (all versions of Borland) NIL is a // reserved, (the equivalent of NULL in Ansi C) word and un-sets any pointer // variable. Setting the owner to the application object will ensure that the form is // freed by the application object when the application shuts down. If I had set // the owner to NIL then i would have had to make sure I freed the form explicitly // or it would have been orphaned, thus creating a memory leak.
// I must direct your attention to the CreateNew constructor. This is // a non standard usage. Normally the constructor Create() will call this // as part of the initialization routine for the form. Normally as you drop // various components on a form in deign mode, a DFM file is created with // all the various initial states of the controls. This bypasses the // DFM file altogether although all components AND the form are created // with default values. (see the Delphi help file).
MainForm := tMainForm.CreateNew(Application); MainForm.Parent := Application ; MainForm.Position := poScreenCenter ; MainForm.Caption := 'Single Window Application' ;
// Create the Label, set its owner as MaiaForm aLabel := tLabel.Create(mainForm); aLabel.Parent := MainForm; aLabel.Caption := IntToStr(i) + ' Clicks since startup' ; aLabel.Left := 20 ; aLabel.Top := MainForm.ClientRect.Bottom div 2 ;
// Create the button, set its owner to MainForm aButton := tButton.Create(MainForm); aButton.Parent := MainForm ; aButton.Caption := 'Click Me!'; aButton.Left := (MainForm.ClientRect.Right div 2)-(aButton.Width div 2 ); aButton.Top := MainForm.ClientRect.Bottom - aButton.Height - 10 ; aButton.OnClick := AddClicks ;
// Show the main form, Modaly. The ONLY reason to do this is because in this // demonstration if you only call the SHOW method, the form will appear and // disappear in a split second. MainForm.ShowModal ; Application.Run ;
end. // Program
</lang>
E
when (currentVat.morphInto("awt")) -> { var clicks := 0 def w := <swing:makeJFrame>("Rosetta Code 'Simple Windowed Application'") w.setContentPane(JPanel` ${def l := <swing:makeJLabel>("There have been no clicks yet.")} $\ ${def b := <swing:makeJButton>("Click Me")} `) b.addActionListener(def _ { to actionPerformed(_) { clicks += 1 l.setText(`Number of clicks: $clicks`) } }) w.pack() w.show() }
Forth
also minos text-label ptr click-label Variable click# click# off : click-win ( -- ) screen self window new window with X" There have been no clicks yet" text-label new dup F bind click-label ^ S[ 1 click# +! click# @ 0 <# #S s" Number of clicks: " holds #> click-label assign ]S X" Click me" button new &2 vabox new panel s" Clicks" assign show endwith ; click-win
The same with Theseus
#! xbigforth \ automatic generated code \ do not edit also editor also minos also forth component class ccount public: early widget early open early dialog early open-app text-label ptr click# ( [varstart] ) cell var clicks ( [varend] ) how: : open new DF[ 0 ]DF s" Click counter" open-component ; : dialog new DF[ 0 ]DF s" Click counter" open-dialog ; : open-app new DF[ 0 ]DF s" Click counter" open-application ; class; ccount implements ( [methodstart] ) ( [methodend] ) : widget ( [dumpstart] ) X" There have been no clicks yet" text-label new ^^bind click# ^^ S[ 1 clicks +! clicks @ 0 <# #S s" Number of clicks: " holds #> click# assign ]S ( MINOS ) X" Click me" button new &2 vabox new panel ( [dumpend] ) ; : init ^>^^ assign widget 1 :: init ; class; : main ccount open-app $1 0 ?DO stop LOOP bye ; script? [IF] main [THEN] previous previous previous
Groovy
import groovy.swing.SwingBuilder def countLabel, count = 0, swing = new SwingBuilder() def frame = swing.frame(title:'Click frame') { flowLayout() countLabel = label(text:"There have been no clicks yet." ) button(text:'Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."}) } frame.pack() frame.show()
IDL
pro counter, ev widget_control, ev.top, get_uvalue=tst tst[1] = tst[1]+1 widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)') widget_control, ev.top, set_uvalue=tst end id = widget_base(title = 'Window Title',column=1) ld = widget_label(id, value = 'There have been no clicks yet.') widget_control, /realize, id, set_uvalue=[ld,0] dummy = widget_button(id,value=' Click Me ',event_pro='counter') xmanager, "Simple", Id end
J
SIMPLEAPP=: 0 : 0 pc simpleApp; xywh 136 8 44 12;cc inc button;cn "Click me"; xywh 136 23 44 12;cc cancel button;cn "Cancel"; xywh 7 10 115 11;cc shownText static;cn "There have been no clicks yet."; pas 6 6;pcenter; rem form end; ) simpleApp_run=: 3 : 0 wd SIMPLEAPP simpleApp_accum=: 0 NB. initialize accumulator wd 'pshow;' ) simpleApp_close=: 3 : 0 wd'pclose' ) simpleApp_cancel_button=: 3 : 0 simpleApp_close'' ) simpleApp_inc_button=: 3 : 0 wd 'set shownText *','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum ) simpleApp_run''
Java
<lang java>import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Clicks extends JFrame implements ActionListener{ private long clicks = 0; private JLabel label; private JButton clicker; private String text;
public Clicks(){ text = "There have been no clicks yet"; label = new JLabel(text); clicker = new JButton("click me"); clicker.addActionListener(this);//listen to the button setLayout(new BorderLayout());//handles placement of components add(label,BorderLayout.CENTER);//add the label to the biggest section add(clicker,BorderLayout.SOUTH);//put the button underneath it setSize(300,200);//stretch out the window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X" setVisible(true);//show it } public static void main(String[] args){ new Clicks();//call the constructor where all the magic happens } public void actionPerformed(ActionEvent arg0) { if(arg0.getSource() == clicker){//if they clicked the button text = "There have been " + (++clicks) + " clicks"; label.setText(text);//change the text }
} }</lang>
MAXScript
rollout buttonClick "Button Click" ( label l "There have been no clicks yet" button clickMe "Click me" local clickCount = 0 on clickMe pressed do ( clickCount += 1 l.text = ("Number of clicks: " + clickCount as string) ) ) createDialog buttonClick
Objective-C
<lang objc>#include <Foundation/Foundation.h>
- include <AppKit/AppKit.h>
@interface ClickMe : NSWindow {
NSButton *button; NSTextField *text; int counter;
} - (void)applicationDidFinishLaunching: (NSNotification *)notification; - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; - (void)advanceCounter: (id)sender; @end</lang>
<lang objc>@implementation ClickMe : NSWindow -(id) init {
NSRect buttonRect; int totalWindowHeight;
counter = 0; button = [[NSButton alloc] init]; [button setButtonType: NSToggleButton]; [button setTitle: @"Click Me"]; [button sizeToFit]; [button setTarget: self]; [button setAction: @selector(advanceCounter:)]; buttonRect = [button frame];
text = [[NSTextField alloc]
initWithFrame: NSMakeRect(buttonRect.origin.x, buttonRect.size.height, buttonRect.size.width, buttonRect.size.height)];
[text setAlignment: NSCenterTextAlignment]; [text setEditable: NO]; [text setStringValue: @"There have been no clicks yet"]; [text sizeToFit];
// reset size of button according to size of (larger...?) text [button setFrameSize: NSMakeSize( [text frame].size.width, buttonRect.size.height ) ];
totalWindowHeight = buttonRect.size.height + [text frame].size.height;
[self initWithContentRect: NSMakeRect(100, 100,
[text frame].size.width, totalWindowHeight)
styleMask: (NSTitledWindowMask | NSClosableWindowMask) backing: NSBackingStoreBuffered defer: NO];
[[self contentView] addSubview: text]; [text release]; [[self contentView] addSubview: button]; [button release];
[self setTitle: @"Click Me!"]; [self center];
return self;
}
-(void) dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching: (NSNotification *)notification {
[self orderFront: self];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification {
return YES;
}
- (void)advanceCounter: (id)sender {
counter++; [text setStringValue: [NSString stringWithFormat: @"Clicked %d times", counter]];
} @end
int main()
{
ClickMe *clickme; NSAutoreleasePool *pool; NSApplication *app;
pool = [[NSAutoreleasePool alloc] init]; app = [NSApplication sharedApplication]; clickme = [[ClickMe alloc] init]; [app setDelegate: clickme]; [app run]; return 0;
}</lang>
Perl
<lang perl> use Tk;
$main = MainWindow->new; $l = $main->Label('-text' => 'There have been no clicks yet.')->pack; $count = 0; $main->Button( -text => ' Click Me ', -command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); }, )->pack; MainLoop();</lang>
<lang perl> use Gtk '-init';
# Window. $window = Gtk::Window->new; $window->signal_connect('destroy' => sub { Gtk->main_quit; }); # VBox. $vbox = Gtk::VBox->new(0, 0); $window->add($vbox); # Label. $label = Gtk::Label->new('There have been no clicks yet.'); $vbox->add($label); # Button. $count = 0; $button = Gtk::Button->new(' Click Me '); $vbox->add($button); $button->signal_connect('clicked', sub { $label->set_text(++$count); }); # Show. $window->show_all; # Main loop. Gtk->main;</lang>
Python
<lang python>from Tkinter import Tk, Label, Button
def update_label():
global n n += 1 l["text"] = "Number of clicks: %d" % n
w = Tk() n = 0 l = Label(w, text="There have been no clicks yet") l.pack() Button(w, text="click me", command=update_label).pack() w.mainloop()</lang>
The same in OO manner
<lang python>#!/usr/bin/env python from Tkinter import Button, Frame, Label, Pack
class ClickCounter(Frame):
def click(self): self.count += 1 self.label['text'] = 'Number of clicks: %d' % self.count def createWidgets(self): self.label = Label(self, text='here have been no clicks yet') self.label.pack() self.button = Button(self, text='click me', command=self.click) self.button.pack() def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() self.count = 0
if __name__=="__main__":
ClickCounter().mainloop()</lang>
<lang python>import sys from qt import *
def update_label():
global i i += 1 lbl.setText("Number of clicks: %i" % i)
i = 0 app = QApplication(sys.argv) win = QWidget() win.resize(200, 100) lbl = QLabel("There have been no clicks yet", win) lbl.setGeometry(0, 15, 200, 25) btn = QPushButton("click me", win) btn.setGeometry(50, 50, 100, 25) btn.connect(btn, SIGNAL("clicked()"), update_label) win.show() app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) app.exec_loop()</lang>
<lang python>import wx
class MyApp(wx.App):
def click(self, event): self.count += 1 self.label.SetLabel("Count: %d" % self.count)
def OnInit(self): frame = wx.Frame(None, wx.ID_ANY, "Hello from wxPython") self.count = 0 self.button = wx.Button(frame, wx.ID_ANY, "Click me!") self.label = wx.StaticText(frame, wx.ID_ANY, "Count: 0") self.Bind(wx.EVT_BUTTON, self.click, self.button) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.button, True, wx.EXPAND) self.sizer.Add(self.label, True, wx.EXPAND) frame.SetSizer(self.sizer) frame.SetAutoLayout(True) self.sizer.Fit(frame) frame.Show(True) self.SetTopWindow(frame) return True
app = MyApp(0) app.MainLoop()</lang>
RapidQ
RapidQ has form designer that produces RapidQ Basic source code. You can get the same result by writing the code yourself with a text editor. Then compile it either from within IDE or by using the command line compiler.
<lang rapidq> DECLARE SUB buttonClick
CREATE form AS QForm Center Height = 120 Width = 300 CREATE text AS QLabel Caption = "There have been no clicks yet." Left = 30: Top = 20 END CREATE CREATE button1 AS QButton Caption = "Click me" Left = 100: Top = 50: Height = 25: Width = 100 OnClick = buttonClick END CREATE END CREATE SUB buttonClick STATIC count AS Integer count = count+1 text.Caption = "Clicked " + STR$(count) + " times." END SUB form.ShowModal</lang>
Ruby
<lang ruby>require 'tk' str = TkVariable.new("no clicks yet") count = 0 root = TkRoot.new TkLabel.new(root, "textvariable" => str).pack TkButton.new(root) do
text "click me" command {str.value = count += 1} pack
end Tk.mainloop</lang>
Tcl
<lang tcl>package require Tk pack [label .l -text "There have been no clicks yet"] set count 0 pack [button .b -text "click me" -command upd] proc upd {} {
.l configure -text "Number of clicks: [incr ::count]"
}</lang>
Vedit macro language
Reg_Set(10, "There have been no clicks yet") #1 = 0 repeat (ALL) { #2 = Dialog_Input_1(3, "`Simple Windowed Application`, `|@(10)`, `[&Click me]`,`[&Exit]`", APP+CENTER, 0, 0) if (#2 != 1) { break } // ESC or Exit #1++ Num_Str(#1, 10) Reg_Set(10, "Clicked", INSERT) Reg_Set(10, " times", APPEND) }