Changing the Value of a label from a list. - list

I am trying to make a guessing game where the program will display a sequence of a number one at a time. I have the sequence randomly generated from a list but I have not been able to display the values in the list one at a time. I want to change the label using bind but I can't seem to make it work.
public class Tutorial extends Application {
Stage window;
Scene scene1, scene2;
Label label;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
//Scene 1
Label welcome = new Label("Welcome to the Guessing Game. Press Start to Enter");
Button start = new Button("Start");
VBox firstlayout = new VBox(10);
firstlayout.getChildren().addAll(welcome, start);
firstlayout.setAlignment(Pos.CENTER);
start.setOnAction(e -> window.setScene(scene2));
scene1 = new Scene(firstlayout, 450, 300);
window.setScene(scene1);
ArrayList<Integer> guessList = numbergen();
Label label = new Label(Integer.toString(getValues(guessList)));
label.setStyle("-fx-text-fill: red; -fx-padding: 10px; -fx-font-size: 50px");
FadeTransition fader = createFader(label);
SequentialTransition Fader = new SequentialTransition(
label,
fader
);
StackPane layout = new StackPane();
layout.getChildren().addAll(label);
scene2 = new Scene(layout, 250, 300);
Fader.play();
window.setTitle("Program Close");
window.setScene(scene1);
window.show();
}
private FadeTransition createFader(Node node) {
FadeTransition fade = new FadeTransition(Duration.seconds(5), node);
fade.setFromValue(1);
fade.setToValue(0);
return fade;
}
public ArrayList<Integer> numbergen(){
ArrayList<Integer> numb = new ArrayList<Integer>();
Random rand = new Random();
for(int i = 0; i<4; i++){
int n = rand.nextInt(5) + 1;
numb.add(n);
}
return numb;
}
public boolean result(ArrayList<Integer> solnList, ArrayList<Integer> guessList){
if(solnList.size() != guessList.size()){
return false;
}else{
for(int i = 0; i<solnList.size(); i++){
if(solnList.get(i) != guessList.get(i)){
return false;
}
}
return true;
}
}
public int getValues(ArrayList<Integer> list){
for(int i = 0; i<list.size(); i++){
return list.get(i);
}
return 0;
}
}

If you want a binding to an integer list element, you can use:
Bindings.integerValueAt(observableList, observableIndex)
For example:
label.textProperty().bind(
Bindings.integerValueAt(observableList, observableIndex).asString()
);
where observableIndex in an IntegerProperty which refers to the current index of an element in the list whose value you wish to be bound to.
When you call observableIndex.add(1), then the binding value will change appropriately.

Related

list does not scroll while extending container in lwuit

List does not scroll while adding images in container. I have a list that extends container. I have used two containers for setting image field(left) and text filed(right). while I am adding text filed container list scrolls properly but while adding images in left field it did not scroll please help me . Thank you for your help.
//List declaration
orgNames = new List(tempName);
WidgetRenderer listCheckBoxRenderer = new WidgetRenderer();
orgNames.setListCellRenderer(listCheckBoxRenderer);
orgNames.setFixedSelection(List.FIXED_TRAIL);
organizationDetailsForm.addComponent(orgNames);
OrganizationNameListener orgNameList = new OrganizationNameListener();
orgNames.addActionListener(orgNameList);
//List renderer class
class WidgetRenderer extends Container implements ListCellRenderer {
private Image[] images;
private Button orgImgButton;
private Image orgImg;
private Container contImage, contDet;
private Label orgNameLabel, locationLabel, ratingLabel;
public WidgetRenderer() {
super();
try {
setLayout(new BorderLayout());
contDet = new Container(new BoxLayout(BoxLayout.Y_AXIS));
contImage = new Container();
contDet.setScrollableY(true);
contImage.setScrollable(true);
contDet.setScrollable(true);
contImage.setScrollable(true);
contDet.setSmoothScrolling(true);
contImage.setSmoothScrolling(true);
setScrollable(true);
setScrollableY(true);
orgImgButton = new Button();
orgNameLabel = new Label();
locationLabel = new Label();
Style orgStyle = new Style();
Style locStyle = new Style();
Font font = Font.createSystemFont(Font.FACE_MONOSPACE,
Font.STYLE_BOLD, Font.SIZE_MEDIUM);
orgStyle.setFont(font);
orgNameLabel.setSelectedStyle(orgStyle);
orgNameLabel.setPressedStyle(orgStyle);
orgNameLabel.setUnselectedStyle(orgStyle);
Font font1 = Font.createSystemFont(Font.FACE_MONOSPACE,
Font.STYLE_PLAIN, Font.SIZE_SMALL);
locStyle.setFont(font1);
locationLabel.setSelectedStyle(locStyle);
locationLabel.setPressedStyle(locStyle);
locationLabel.setUnselectedStyle(locStyle);
ratingLabel = new Label();
contImage.addComponent(orgImgButton);
contDet.addComponent(orgNameLabel);
contDet.addComponent(locationLabel);
addComponent(BorderLayout.WEST, contImage);
addComponent(BorderLayout.CENTER, contDet);
} catch (Exception ex) {
System.out.println("ex" + ex.getMessage());
}
}
public Component getListCellRendererComponent(List list, Object value,
int index, boolean isSelected) {
// System.out.println("adding names & loc");
setFocus(isSelected);
for (int i = 0; i < list.size(); i++) {
if (index == i) {
orgNameLabel.setText(tempName[i]);
locationLabel.setText(districtDesc[i] + "," + townDesc[i]);
orgImgButton.setIcon(DefaultLayout.CreateScaledImage(loadImage(thumbnailURL), DefaultLayout.screenWidth()*10/100, DefaultLayout.screenHeight()*9/100));
}
}
if (isSelected) {
getStyle().setBgColor(0x00BFFF);
getStyle().setBgTransparency(100);
} else {
getStyle().setBgTransparency(30);
}
return this;
}
You are invoking scaled() which is a VERY slow and expensive operation within a renderer which must be REALLY fast. Not a good idea. Not sure if that answers your issue but I suggest investigating whether the TRAIL flag is the cause of your issue.

How to set up a string array with strings that would display through the array on a text for iphone?

I'm new to iphone development but I have done android before. The following is something I have done in java and I want to convert this over to iphone.
public class RelationshipTipsActivity extends Activity implements
OnClickListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
String facts[] = {"Coming soon",
"Coming soon", };
TextView display, display1;
TextView counter;
Button begin;
Button next;
Button previous;
Button random;
Random myRandom;
int index = facts.length;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(starting.rt.R.layout.relationship);
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
display1 = (TextView) findViewById(starting.rt.R.id.Begin);
display = (TextView) findViewById(starting.rt.R.id.tvResults);
counter = (TextView) findViewById(starting.rt.R.id.tvCounter);
next = (Button) findViewById(starting.rt.R.id.Next);
previous = (Button) findViewById(starting.rt.R.id.Previous);
random = (Button) findViewById(starting.rt.R.id.Random);
next.setOnClickListener(this);
previous.setOnClickListener(this);
random.setOnClickListener(this);
// display.setOnTouchListener(this.gestureListener);
myRandom = new Random();
// gestureDetector = new GestureDetector(new MyGestureDetector());
// gestureListener = new View.OnTouchListener() {
// public boolean onTouch(View v, MotionEvent event) {
// return gestureDetector.onTouchEvent(event);
// }
// };
}
private void showDisplay() {
display.setText(facts[index]);
counter.setText(String.valueOf(index + 1) + "/"
+ String.valueOf(facts.length));
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case starting.rt.R.id.Next:
index++;
if (index > facts.length - 1) {
index = 0;
}
showDisplay();
break;
case starting.rt.R.id.Previous:
index--;
if (index < 0) {
index = facts.length - 1;
}
showDisplay();
break;
case starting.rt.R.id.Random:
index = (myRandom.nextInt(facts.length) - 1);
if (index < 0) {
index = facts.length - 1;
}
showDisplay();
break;
}
}
}
How would you convert something along the lines of that code from android to iphone.
I have this code so far for iphone, I just don't know where to go from there.
(IBAction) clicked:(id)sender{
NSArray *titleOfButton = [sender titleForState:UIControlStateNormal];
//NSString *newLabelText = [[NSString alloc]initWithFormat:#"%#", titleOfButton];
NSArray *initializedNSArray = [NSArray arrayWithObjects: #"red",
#"blue",
#"green",
#"yellow",
nil];
labelsText.text = initializedNSArray;
[initializedNSArray release];
}
I want to be able to display those strings within the Iphone View. And be able to click a next or previous button to go to the next or previous string which could be from blue to red or red to blue. Basically if there are any tutorials out there that help me with that or if you know how to help I would appreciate. Thanks!
Why not have a int variable with the current position of the string from the array and two methods goPrev - goNext that increments and decrements the int variable.
In the interface:
UIButton *btn;
int step;
NSArray *titles;
And in the implementation:
-(void)setup {
titles = [NSArray arrayWithObjects:#"Title 1",#"Title 2",#"Title 3",#"Title 4", nil];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
}
-(void)goPrev {
if (step>0) {
step--;
}
[btn setTitle:[titles objectAtIndex:step] forState:UIControlStateNormal];
}
-(void)goNext {
if (step<titles.count-1) {
step++;
}
[btn setTitle:[titles objectAtIndex:step] forState:UIControlStateNormal];
}

How to use the CCTimer class in Cocos2d android?

I want to use CCTimer class for the Timer but I can't sort out. After I use to manually create a function for this but it seems not effective .
protected GameLayer(ccColor4B color)
{
super(color);
schedule(new UpdateCallback() {
#Override
public void update(float d) {
countTime(d);
}
},0.99f);
}
public void countTime(float scr) {
if(_label != null){
this.removeChild(_label,true);
}
j=j-(int)scr;
CGSize winSize = CCDirector.sharedDirector().displaySize();
_label = CCLabel.makeLabel("Time Left :" + j, "Verdana", 20);
_label.setColor(ccColor3B.ccGREEN);
_label.setPosition(155f, winSize.height - 15);
addChild(_label);
if(j<=0){
CCDirector.sharedDirector().pause();
}
}
it run from 1 to the the point which i want to stop ... !!!
what should i do to use the CCTimer class to resolve this problem ?
CCTimer is available but I haven't tried this earlier but you can do this thing through Timer class :
Timer timer = new Timer();
timer.scheduleAtFixedRate( new TimerTask(){
public void run() {
updateTimeLabel();
}
public void updateTimeLabel() {
float time += 1;
String string = CCFormatter.format("%02d:%02d", (int)(time /60) , (int)time % 60 );
CCBitmapFontAtlas timerLabel = (CCBitmapFontAtlas) getChildByTag(TIMER_LABEL_TAG) ;
timerLabel.setString(string);
}

OOP Game Menu System Development Conceptualising

I'm trying to write an OO menu system for a game, loosely based on the idea of a Model,View,Controller. In my app so far I've named the views "renderers" and the models are without a suffix. I created a generic menu class which stores the items of a menu, which are menu_item objects, and there is also a menu renderer class which creates renderers for each item and renders them. The problem is I'm not sure where to store the data and logic to do with where on the screen each item should be positioned, and how to check if it is being hovered over, etc. My original idea was to store and set a selected property on each menu item, which could be rendered differently by different views, but even then how to I deal with positioning the graphical elements that make up the button?
Code excerpts so far follow: (more code at https://gist.github.com/3422226)
/**
* Abstract menu model
*
* Menus have many items and have properties such as a title
*/
class menu {
protected:
std::string _title;
std::vector<menu_item*> _items;
public:
std::string get_title();
void set_title(std::string);
std::vector<menu_item*> get_items();
};
class menu_controller: public controller {
private:
menu* _menu;
public:
menu_controller(menu*);
virtual void update();
};
class menu_item {
protected:
std::string _title;
public:
menu_item(std::string title);
virtual ~menu_item();
std::string get_title();
};
class menu_renderer: public renderer {
private:
menu* _menu;
bitmap _background_bitmap;
static font _title_font;
std::map<menu_item*, menu_item_renderer*> _item_renderers;
public:
menu_renderer(menu*);
virtual void render();
};
font menu_renderer::_title_font = NULL;
menu_renderer::menu_renderer(menu* menu) {
_menu = menu;
_background_bitmap = ::load_bitmap("blackjack_menu_bg.jpg");
if (!_title_font)
_title_font = ::load_font("maven_pro_regular.ttf",48);
}
void menu_renderer::render() {
::draw_bitmap(_background_bitmap, 0, 0);
/* Draw the menu title */
const char* title = _menu->get_title().c_str();
int title_width = ::text_width(_title_font, title);
::draw_text(title, color_white, _title_font, screen_width() - title_width - 20, 20);
/* Render each menu item */
std::vector<menu_item*> items = _menu->get_items();
for (std::vector<menu_item*>::iterator it = items.begin(); it != items.end(); ++it) {
menu_item* item = *it;
if (!_item_renderers.count(item))
_item_renderers[item] = new menu_item_renderer(item, it - items.begin());
_item_renderers[item]->render();
}
}
class menu_item_renderer: public renderer {
private:
unsigned _order;
menu_item* _item;
static font _title_font;
public:
menu_item_renderer(menu_item*, unsigned);
virtual ~menu_item_renderer();
virtual void render();
};
font menu_item_renderer::_title_font = NULL;
menu_item_renderer::menu_item_renderer(menu_item* item, unsigned order) {
_item = item;
_order = order;
if (!_title_font)
_title_font = ::load_font("maven_pro_regular.ttf",24);
}
menu_item_renderer::~menu_item_renderer() {
// TODO Auto-generated destructor stub
}
void menu_item_renderer::render() {
const char* title = _item->get_title().c_str();
int title_width = ::text_width(_title_font, title);
unsigned y = 44 * _order + 20;
::fill_rectangle(color_red, 20, y, title_width + 40, 34);
::draw_text(title, color_white, _title_font, 30, y + 5);
}
Your Model class menu needs a add_view(menuview *v) and update() method.
Then you can delegate the update of your widget to the derived View (menu_renderer or a cli_menu_renderer).
The Controller needs to know the Model (as member), when the Controller runs (or executes a Command) and has to update the Model with a Setter (like m_menu_model->set_selected(item, state)) and the Model calls update() on Setters.
Your Controller menu_controller has a update method, there you could also ask for Input, like if (menuview->toggle_select()) m_menu_model->toggle_selected(); (which all menuviews have to implement) and invoke the setter, but thats a inflexible coupling of View and Controller (you could check MVC with the Command Pattern for a more advanced combination).
For the Position you can set member vars like int m_x, m_y, m_w, m_h.
But these members are specific to a View with GUI, so only the derived View needs them.
Then you could use these values to compare against mouse Positions and use a MouseOver Detection Method like this:
// View menu_item
bool menu_item::over()
{
if (::mouse_x > m_x
&& ::mouse_x < m_x + m_w
&& ::mouse_y > m_y
&& ::mouse_y < m_y + m_h) {
return true;
}
return false;
}
// update on gui menu item
bool menu_item::update()
{
if (over()) {
m_over = true;
}
else {
m_over = false;
}
// onclick for the idea
if ((::mouse_b & 1) && m_over) {
// here you could invoke a callback or fire event
m_selected = 1;
} else {
m_selected = 0;
}
return m_selected;
}
// update the command line interface menu item
bool cli_menu_item::update()
{
if ((::enterKeyPressed & 1) && m_selected) {
// here you could invoke a callback or fire event
m_selected = 1;
} else {
m_selected = 0;
}
return m_selected;
}
void menu_item_renderer::render() {
// update widgets
_item->update();
// ...
}
// Model
void menu::add_view(menuview *v) {
m_view=v;
}
void menu::update() {
if (m_view) m_view->update();
}
bool menu::set_selected(int item, int state) {
m_item[index]=state;
update();
}

Maintaining checkedstatus inheritance in a QTreeView

I'm trying to do something basic : you have a QTreeView. 1st depth are folders only, 2nd depth are files only. I want to have a check box with the checked status next to each item. Files are either checked or unchecked, folders can also be partiallyChecked depending on their files; all in all quite natural I believe.
The way I though I should go was using a QStandardItemModel and populate it with a custom subclass of QStandardItem : DescriptionFileItem. Maybe that was a bad idea, if there's an easier way please enlight me.
I tried using signals and slots so that my signal CheckStateChanged on a file would be connected to a slot UpdateCheckedStateOnChildStateChanged on its containing folder. This required my DescriptionFileItem to inherit from QObject as well (BTW, I was surprised that QStandardItem did not inherit from QObject). I initially hoped this would work seamlessly with the provided base classes but it did not : emitDataChanged() didn't seem to trigger my model's dataChanged() signal...
Using the model's dataChanged signals directly didn't work either: it's call is protected so you can't use it without subclassing (I think that's my next move unless somebody can help me get it right).
At the moment I have a signal -> slot connection that won't work and I have no idea why; compile and link work ok. Here's the code; perhapps you'll spot my mistakes easily. I'm leaving some commented lines so you can maybe see what I did wrong in a previous attempt. Thanks for your input!
#ifndef DESCRIPTIONFILEITEM_H
#define DESCRIPTIONFILEITEM_H
#include <QStandardItem>
#include <Qt>
class DescriptionFileItem : public QObject, public QStandardItem
{
Q_OBJECT
public:
explicit DescriptionFileItem(const QString & text, bool isFileName=false, QObject* parent = 0);
void setData ( const QVariant & value, int role = Qt::UserRole + 1 );
QVariant data( int role = Qt::UserRole + 1 ) const;
QString text;
Qt::CheckState checkedState;
bool isFileName;
signals:
void CheckStateChanged();
public slots:
void UpdateCheckedStateOnChildStateChanged();
};
#endif // DESCRIPTIONFILEITEM_H
Corresponding .cpp :
#include "DescriptionFileItem.h"
DescriptionFileItem::DescriptionFileItem(const QString & text, bool isFileName, QObject* parent):
QObject(parent),QStandardItem(text)
{
this->isFileName = isFileName;
checkedState = Qt::Checked;
}
void DescriptionFileItem::setData ( const QVariant & value, int role){
if(role == Qt::CheckStateRole){
Qt::CheckState newCheckState = (Qt::CheckState)value.toInt();
checkedState = newCheckState;
if(isFileName){
if(newCheckState == Qt::Unchecked || newCheckState == Qt::Checked){
for(int i = 0; i<rowCount(); i++){
DescriptionFileItem* child = (DescriptionFileItem*)QStandardItem::child(i);
QModelIndex childIndex = child->index();
child->model()->setData(childIndex,newCheckState, Qt::CheckStateRole);
//child->setCheckState(newCheckState);
//child->setData(newCheckState,Qt::CheckStateRole);
}
/*if(rowCount()>1){
emit this->model()->dataChanged(this->child(0)->index(),this->child(rowCount()-1)->index());
}else{
emit this->model()->dataChanged(this->child(0)->index(),this->child(0)->index());
}*/
}
}else{
emit CheckStateChanged();
}
//emit this->model()->dataChanged(this->index(),this->index());
}else{
QStandardItem::setData(value,role);
}
}
QVariant DescriptionFileItem::data( int role ) const{
if (role == Qt::CheckStateRole){
return checkedState;
}
return QStandardItem::data(role);
}
void DescriptionFileItem::UpdateCheckedStateOnChildStateChanged()
{
Qt::CheckState min = Qt::Checked;
Qt::CheckState max = Qt::Unchecked;
Qt::CheckState childState;
for(int i = 0; i<rowCount(); i++){
DescriptionFileItem* child = (DescriptionFileItem*)QStandardItem::child(i);
childState = (Qt::CheckState) child->data(Qt::CheckStateRole).toInt();
min = min>childState ? childState: min;
max = max<childState ? childState: max;
}
if(min >= max)
setData(min, Qt::CheckStateRole);
else
setData(Qt::PartiallyChecked, Qt::CheckStateRole);
}
And the construction of the connection / tree:
DescriptionFileItem* descFileStdItem = new DescriptionFileItem(descriptionFileName, true);
descFileStdItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsTristate);
descriptionFileSIModel.appendRow(descFileStdItem);
typedef pair<string,int> indexType;
foreach(indexType index,dataFile->indexes){
DescriptionFileItem* key_xItem = new DescriptionFileItem(index.first.c_str());
descFileStdItem->appendRow(key_xItem);
key_xItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
QObject::connect(key_xItem,SIGNAL(CheckStateChanged()),descFileStdItem,SLOT(UpdateCheckedStateOnModelDataChanged()));
}
EDIT: final answer, thanks to stu (see below)
void DataLoadWidget::ModelItemChanged(QStandardItem *item)
{
QStandardItem* parent = item->parent();
if(parent == 0){
//folder state changed--> update children if not partially selected
Qt::CheckState newState = item->checkState();
if(newState != Qt::PartiallyChecked){
for (int i = 0; i < item->rowCount(); i++)
{
item->child(i)->setCheckState(newState);
}
}
}
else{//child item changed--> count parent's children that are checked
int checkCount = 0;
for (int i = 0; i < parent->rowCount(); i++)
{
if (parent->child(i)->checkState() == Qt::Checked)
checkCount++;
}
if(checkCount == 0)
parent->setCheckState(Qt::Unchecked);
else if (checkCount == parent->rowCount())
parent->setCheckState(Qt::Checked);
else
parent->setCheckState(Qt::PartiallyChecked);
}
}
Unless I've misunderstood your question it seems that your solution is massively over-complicated. You should be able to do this trivially with the default QStandardItemModel implementation.
How about something like this (error handling omitted)?
QObject::connect(model, SIGNAL(itemChanged(QStandardItem*)), someObject, SLOT(modelItemChanged(QStandardItem*)));
And then in the signal handler:
void modelItemChanged(QStandardItem* item)
{
QStandardItem* parent = item->parent();
int checkCount = 0;
int rowCount = parent->rowCount();
for (int i = 0; i < rowCount; i++)
{
if (parent->child(i)->checkState() == Qt::Checked)
checkCount++;
}
switch (checkCount)
{
case 0:
parent->setCheckState(Qt::Unchecked);
break;
case rowCount:
parent->setCheckState(Qt::Checked);
break;
default:
parent->setCheckState(Qt::PartiallyChecked);
}
}
This is by no means optimal but it may be good enough for your purposes.