The user can provide input by typing keys and manipulating the
mouse. An application's window handles keyboard activity
by overriding the
key_pressed
method inherited from
Window
. The SGL event manager directs mouse
events to one of four mouse processing methods:
mouse_pressed
,
mouse_released
, mouse_moved
,
and mouse_dragged
. If the user presses a key on
the keyboard, the event manager calls
the window's key_pressed
method.
Clients override these
methods to provide behavior appropriate for the application.
Example 3.3 allows a user to change the color of a rectangular box by clicking a mouse button or pressing the T (for toggle) key on the keyboard.
Example 3.3. User Input
#include <GL/sgl.hpp> class ColorBox: public sgl::Window { protected: bool is_red; public: ColorBox(): sgl::Window("Click Me", 100, 100, 400, 300, 0.0, 100.0, 0.0, 100.0), is_red(true) {} void paint() override { if (is_red) sgl::set_color(sgl::RED); else sgl::set_color(sgl::BLUE); sgl::fill_rectangle(30.0, 30.0, 40.0, 40.0); } void mouse_pressed(double, double, sgl::MouseButton) override { is_red = !is_red; // Toggle the color repaint(); // Request a repaint } void key_pressed(int key, double x, double y) override { // Did the user press the T key? if (key == 'T' || key == 't') { is_red = !is_red; // Toggle the color repaint(); // Request a repaint } // Call base class method in case user pressed // Alt-F4 to close the window sgl::Window::key_pressed(key, x, y); } }; int main() { // Create a window instance and execute it sgl::run<ColorBox>(); }
Each input handling method will usually include a call to
repaint
.
This is because the user's input
generally affects what the program displays. In the case of
Example 3.3, the user's mouse click is
supposed to change
the color of the box, but the window is repainted only when the
event manager calls the window object's
paint
method. The
repaint
call notifies the event manager that
the contents of the window need to be redrawn. Client code should
not call paint
directly.
Copyright ©2019 Richard L. Halterman | Version 0.9.5 | February 17, 2019 |