00001 /* 00002 * The Mana World 00003 * Copyright (C) 2004 The Mana World Development Team 00004 * 00005 * This file is part of The Mana World. 00006 * 00007 * This program is free software; you can redistribute it and/or modify 00008 * it under the terms of the GNU General Public License as published by 00009 * the Free Software Foundation; either version 2 of the License, or 00010 * any later version. 00011 * 00012 * This program is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU General Public License 00018 * along with this program; if not, write to the Free Software 00019 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 00020 */ 00021 00022 #include "gui/widgets/inttextfield.h" 00023 00024 #include "gui/sdlinput.h" 00025 00026 #include "utils/stringutils.h" 00027 00028 IntTextField::IntTextField(int def): 00029 TextField(toString(def)), 00030 mDefault(def), 00031 mValue(def) 00032 { 00033 } 00034 00035 void IntTextField::keyPressed(gcn::KeyEvent &event) 00036 { 00037 const gcn::Key &key = event.getKey(); 00038 00039 if (key.getValue() == Key::BACKSPACE || 00040 key.getValue() == Key::DELETE) 00041 { 00042 setText(std::string()); 00043 event.consume(); 00044 } 00045 00046 if (!key.isNumber()) 00047 return; 00048 00049 TextField::keyPressed(event); 00050 00051 std::istringstream s(getText()); 00052 int i; 00053 s >> i; 00054 setValue(i); 00055 } 00056 00057 void IntTextField::setRange(int min, int max) 00058 { 00059 mMin = min; 00060 mMax = max; 00061 00062 if (mValue < mMin) 00063 mValue = mMin; 00064 else if (mValue > mMax) 00065 mValue = mMax; 00066 00067 if (mDefault < mMin) 00068 mDefault = mMin; 00069 else if (mDefault > mMax) 00070 mDefault = mMax; 00071 } 00072 00073 int IntTextField::getValue() 00074 { 00075 return getText().empty() ? mMin : mValue; 00076 } 00077 00078 void IntTextField::setValue(int i) 00079 { 00080 if (i < mMin) 00081 mValue = mMin; 00082 else if (i > mMax) 00083 mValue = mMax; 00084 else 00085 mValue = i; 00086 00087 const std::string valStr = toString(mValue); 00088 setText(valStr); 00089 setCaretPosition(valStr.length() + 1); 00090 } 00091 00092 void IntTextField::setDefaultValue(int value) 00093 { 00094 if (value < mMin) 00095 mDefault = mMin; 00096 else if (value > mMax) 00097 mDefault = mMax; 00098 else 00099 mDefault = value; 00100 } 00101 00102 void IntTextField::reset() 00103 { 00104 setValue(mDefault); 00105 }