I'm trying to make a Menu object. So far I've only added the buttons, which contain a RectangleShape body and Text. When trying to draw the text portion of a button to the window I get errors.
//MenuTest.h
#include <SFML/Graphics.hpp>
#include <string>
#include <vector>
class Menu1
{
class Button1
{
sf::RectangleShape body;
sf::Text text;
void create(float x, float y);//sets button postion
void setText();//ensures text is centered inside the button
public:
void setPosition(float x, float y);
void drawButton(sf::RenderWindow &window);
Button1(float w, float h, float x, float y, sf::Font f, std::string s="Button")
: body(sf::Vector2f(w,h)), text(s,f) {create(x,y);}
};
std::vector<Button1> MenuButtons;
public:
void draw(sf::RenderWindow &window);
void addButton(float w, float h, float x, float y, sf::Font f, std::string s="Button");
};
#include "MenuTest.h"
//Button1---
void Menu1::Button1::create(float x, float y)
{
body.setOutlineThickness(-2);
body.setFillColor(sf::Color::Black);
body.setOutlineColor(sf::Color::White);
setPosition(x,y);
}
void Menu1::Button1::setText()
{
//lot of code that makes sure text is aligned inside the button
//confirmed that this has no effect on the issue
}
void Menu1::Button1::setPosition(float x, float y)
{
body.setPosition(x,y);
setText();
}
void Menu1::Button1::drawButton(sf::RenderWindow &window)
{
window.draw(body);
window.draw(text);//<--- Error comes from here
}
//Menu1----
void Menu1::addButton(float w, float h, float x, float y, sf::Font f, std::string s)
{
MenuButtons.push_back(Button1(w,h,x,y,f,s));
}
void Menu1::draw(sf::RenderWindow &window)
{
for(int i=0;i<MenuButtons.size();i++)
MenuButtons[i].drawButton(window);
}
#include "MenuTest.h"
#include <iostream>
void createMenu(sf::RenderWindow &window)
{
Menu1 main;
sf::Font font;
if(!font.loadFromFile("Terminal.ttf"))
std::cout<<"Font error\n";
main.addButton(100,50,20,20,font);
main.draw(window);
}
int main()
{
sf::RenderWindow window(sf::VideoMode(1000,800),"Window");
window.clear();
createMenu(window);
window.display();
char a;
std::cin>>a;
window.close();
return 0;
}
This causes an error at the line
window.draw(text);
in Menu::Button::drawButton(). With the error "Access violation reading location (some memory address)"
I have confirmed that everything works up until the draw text line. I have also confirmed that the neither the setText function nor the vector are causing the problem by having Menu1 store just one button by itself and setting the text to some arbitrary point. The error still occurs. I've been looking a this for awhile and I'm at a loss as to what is happening.
Thanks for any help/suggestions.