I´m new to FLTK and currently facing the following problem:
I have a class PointModel, which stores points with x- and y-coordinates, a class View, which needs to call update(), everytime the coordinates in the PointModel change (Observer Pattern) and draw them and finally a class MyBox, where the coordinates should be drawn in.
View is derived from Fl_Window. MyBox is derived from Fl_Box and part of View.
Therefore I need to know, how to pass the point coordinates from a member function (void update()) of View to the draw method of MyBox.
I´m trying to typecast the user_data pointer I get to View* in case to be able to get the PointModel, holding the point coordinates. But the window closes after calling the draw() method. Maybe I only get a NULL-Pointer here? Unfortunately I can´t check it through debugging, because somehow Eclipse doesn´t break at the breakpoints now..
Any solutions, hints what I´m doing wrong or possible alternatives?
Thanks in advance!
Here some pieces of my code:
class MyBox : public Fl_Box {
void draw() {
Fl_Box::draw();
View *v1 = (View*)this->parent();
if(v1 != NULL) {
int lastX = v1->getPointModel()->getLastX();
int lastY = v1->getPointModel()->getLastY();
int currentX = v1->getPointModel()->getCurrentX();
int currentY = v1->getPointModel()->getCurrentY();
fl_color(FL_WHITE);
fl_line(lastX, lastY, currentX, currentY);
}
}
public:
MyBox(int X,int Y,int W,int H,const char*L=0) : Fl_Box(X,Y,W,H,L) {
box(FL_FLAT_BOX);
}
};
View::View(*arguments*) :Fl_Window(540,650,"View1") {
begin();
MyBox box(20,20,500,500," ");
box.box(FL_UP_BOX);
box.color(0x00000000);
//more widgets
end();
show();
Fl::add_timeout(3.0, Timer_CB, (void*)this);
Fl::run();
}
edit: I updated the code to running version
Well, MyBox.draw()
will be called before you call add_timeout(). user_data() will give you NULL most likely... You could add a check for NULL in there. Something like:
void draw() {
Fl_Box::draw();
void* ptr = user_data();
if (ptr) {
// do stuff here...
}
Second possible problem is this->parent()->user_data();
. Parent of your MyBox object is the Fl_Window object (actually, your View object, which is a Fl_Window), and user_data() will always return NULL for it I think...
The easiest way to pass any object to your widget is to use user_data() method:
box.user_data(&myview); // after this box.user_data() will return a View*