Slick Forums
http://slick.ninjacave.com/forum/

Unable to create TextField
http://slick.ninjacave.com/forum/viewtopic.php?f=21&t=4735
Page 1 of 1

Author:  ac99 [ Wed Mar 21, 2012 4:11 pm ]
Post subject:  Unable to create TextField

I have been trying to create a textfield on the screen but I always get an error saying that GameContainer should be casted to GUIContext.
I looked at the GUITest, followed it exactly as it was written there and ran into the same problem.

When I cast it, the application just crashes saying that GameContainer can not be casted to GUIContext.

Any help is appreciated.
Thanks

Author:  snakex20 [ Thu Mar 22, 2012 10:43 pm ]
Post subject:  Re: Unable to create TextField

Hello ac99, can I get the source code part when you are trying to create a textfield? I can help you better with that hopefully :? .

Author:  ac99 [ Fri Mar 23, 2012 12:51 am ]
Post subject:  Re: Unable to create TextField

hi,
so i declared all the variables and tried to put it in the init function

Code:
public class nameState extends BasicGameState {

  Font font;
  TextField textField;

  public void init(GameContainer gc, StateBasedGame sb) throws SlickException {
    font = new UnicodeFont(new java.awt.Font("Arial", java.awt.Font.ITALIC, 26));
    textField = new TextField(gc, font, 400, 300, 300, 50);   <- i get a error here and the fix is to cast argument gc to GUIContext
  }
  public void render(GameContainer gc, StateBasedGame sb, Graphics g) throws SlickException {
    textField.render(gc, g);  <- same error i get in init... cast argument gc to GUIContext
  }
}


Thanks

Author:  snakex20 [ Fri Mar 23, 2012 4:03 am ]
Post subject:  Re: Unable to create TextField

I tested it and its working fine with the container's default font. It also ran fine with the font that you put in the parameter exept that you can't see the text. A temporal fix is using the Slick2D default font. BTW, did you imported the following bellow? Idid not have any errors while running your code and my code.

I set the text to "AWSOME" to see the font as a sample.

Code:

import org.newdawn.slick.*;
import org.newdawn.slick.gui.TextField;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class nameState extends BasicGameState {

  Font font;
  TextField textField;

    @Override
  public void init(GameContainer gc, StateBasedGame sb) throws SlickException {
    font = new UnicodeFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.ITALIC, 26));
    textField = new TextField(gc, [color=#4000FF]gc.getDefaultFont(), [/color]400, 300, 300, 50);  // <- i get a error here and the fix is to cast argument gc to GUIContext// i replaced your font in the constructor with the container's default font and it works.
    textField.setText("AWSOME");
  }
  public void render(GameContainer gc, StateBasedGame sb, Graphics g) throws SlickException {
    textField.render(gc, g);  //<- same error i get in init... cast argument gc to GUIContext
  }

    @Override
    public int getID() {
        return 0;    }

    @Override
    public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
      //  throw new UnsupportedOperationException("Not supported yet.");
       
       
    }
}

here the source of the other file i used to test your class. try it out and let me know if you have errors. I think there's a bug using the new UnicodeFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.ITALIC, 26)); im not sure. I remembered I tried to use it long time ago and had problems, so I stay with the default font.


you can try use the following classes for font you gonna put in the constructor of the textfield to see if it works. I havent tested them.
AngelCodeFont, SpriteSheetFont, TrueTypeFont,//(not this one) UnicodeFont //
Code:

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Owner
 */
public class NewClass extends StateBasedGame{

    public NewClass(String name) {
        super(name);
    }

   
    @Override
    public void initStatesList(GameContainer container) throws SlickException {
        addState(new nameState());
    }
    public static void main(String[] v) throws SlickException{
        AppGameContainer n = new AppGameContainer(new NewClass("AWsome"),800,800,false);
        n.start();
    }
   
}




Attachments:
font.png
font.png [ 8.9 KiB | Viewed 11342 times ]

Author:  snakex20 [ Fri Mar 23, 2012 5:19 am ]
Post subject:  Re: Unable to create TextField

I figure out a solution. use the TrueTypeFont class instead of UnicodeFont and it should work all fine. heres a screen shot when i use

Code:
font = new TrueTypeFont(new java.awt.Font(java.awt.Font.SERIF,java.awt.Font.BOLD , 26), false);


Attachments:
font.png
font.png [ 34.81 KiB | Viewed 11340 times ]

Author:  davedes [ Fri Mar 23, 2012 1:59 pm ]
Post subject:  Re: Unable to create TextField

With UnicodeFont you need to call loadGlyphs otherwise it won't show anything. One way to do this (which is slow) is to add all possible glyphs and then load them all at once:
Code:
font.addNeheGlyphs();
font.loadGlyphs();


Another way is to load them per frame; as demonstrated in UnicodeFontTest.

Ideally -- especially for android -- you should use bitmap fonts (i.e. AngelCodeFont or SpriteSheetFont).

Author:  ac99 [ Mon Mar 26, 2012 4:55 pm ]
Post subject:  Re: Unable to create TextField

I copied and pasted everything everyone did and didn't have any success. I ended up with the same result of casting to GUIContext. I then thought about that the slick-ae.jar file that I have been using isn't made properly with textfield... so I removed the build path of slick-ae.jar and added slick.jar to the build path and surprisingly enough it works... No more errors!
I guess it's my slick-ae.jar file that has been causing the problem.

Thanks for the help everyone.
Next step for me... fix the slick-ae.jar file!

Author:  Mr. Kenkron [ Mon Mar 26, 2012 7:17 pm ]
Post subject:  Re: Unable to create TextField

i have not tested your code, but I believe that unicode font uses dynamic textures in the load glyphs method. By this i mean that the computer has to generate the image instead of loading it from a file. So far, I have not managed to get dynamic textures to work on android, but even if i could, there is a problem with dynamic textures on android. whenever the game loses focus, all of the textures are lost. when you resume the game, the textures loaded from files are automatically re-loaded, but dynamic textures are still lost. it may be possible to rebuild the texture when the game resumes, but is much easier to do what davedes recommended: use bitmap fonts.

Author:  davedes [ Mon Mar 26, 2012 8:02 pm ]
Post subject:  Re: Unable to create TextField

Both TrueTypeFont and UnicodeFont use AWT for font rendering... It's a wonder either would work at all on Android. :|

Author:  ac99 [ Mon Apr 30, 2012 3:09 am ]
Post subject:  Re: Unable to create TextField

I'm not sure what I'm doing wrong... but I tried to make a new slick-ae.jar file and i end up with the same problem i had at the beginning.
I also tried to use the gc.getDefaultFont() but I still end up with the same error: "cast argument gc to GUIContext"
(TextField is driving me insane!!!)

Thanks for all the input that has been coming.
Much appreciated.

Author:  mortias [ Tue May 01, 2012 8:43 am ]
Post subject:  Re: Unable to create TextField

i don't think you need to cast it
just override it with the GUIContext as argument cause the gamecontainer is an implementation of that
public void init(GUIContext cxt, StateBasedGame sb) throws SlickException

however i run it with the gamecontainer class..
how does your textfield class look like? probably you took the one from svn,
https://bob.newdawnsoftware.com/svnwebc ... Field.java

just create one that takes the gamecontainer as argument and not guicontext
like this: (or you change in your textfield the constructors from Guicontext to gamecontainer)

Code:
package org.newdawn.slick.gui;

import org.lwjgl.Sys;
import org.newdawn.slick.*;
import org.newdawn.slick.geom.Rectangle;

/**
 * A single text field supporting text entry
 *
 * @author kevin
 */
public class TextField extends AbstractComponent {

    private static final int INITIAL_KEY_REPEAT_INTERVAL = 400;
    private static final int KEY_REPEAT_INTERVAL = 50;

    private int width;
    private int height;
    protected int x;
    protected int y;
    private int maxCharacter = 1000;
    private String value = "";
    private Font font;
    private Color border = Color.white;
    private Color text = Color.white;
    private Color background = new Color(0, 0, 0, 0.5f);
    private int cursorPos;
    private boolean visibleCursor = true;
    private int lastKey = -1;
    private char lastChar = 0;
    private long repeatTimer;
    private String oldText;
    private int oldCursorPos;
    private boolean consume = true;

    public TextField(GameContainer gc, Font font, int x, int y, int width, int height, ComponentListener listener) {
        this(gc, font, x, y, width, height);
        addListener(listener);
    }

    public TextField(GameContainer gc, Font font, int x, int y, int width, int height) {
        super(gc, true);

        this.font = font;

        setLocation(x, y);
        this.width = width;
        this.height = height;
    }

    public void setConsumeEvents(boolean consume) {
        this.consume = consume;
    }

    public void deactivate() {
        setFocus(false);
    }

    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public void setBackgroundColor(Color color) {
        background = color;
    }

    public void setBorderColor(Color color) {
        border = color;
    }

    public void setTextColor(Color color) {
        text = color;
    }

    public void render(GameContainer gc, Graphics g) {
        if (lastKey != -1) {
            if (input.isKeyDown(lastKey)) {
                if (repeatTimer < System.currentTimeMillis()) {
                    repeatTimer = System.currentTimeMillis() + KEY_REPEAT_INTERVAL;
                    keyPressed(lastKey, lastChar);
                }
            } else {
                lastKey = -1;
            }
        }
        Rectangle oldClip = g.getClip();
        // g.setWorldClip(x,y,width, height);

        // Someone could have set a color for me to blend...   
        Color clr = g.getColor();

        if (background != null) {
            g.setColor(background.multiply(clr));
            g.fillRect(x, y, width, height);
        }
        g.setColor(text.multiply(clr));

        int cpos = font.getWidth(value.substring(0, cursorPos));
        int tx = 0;
        if (cpos > width) {
            tx = width - cpos - font.getWidth("_");
        }

        g.translate(tx + 2, 0);
        g.setFont(font);
        g.drawString(value, x + 1, y + 1);

        if (hasFocus() && visibleCursor) {
            g.drawString("_", x + 1 + cpos + 2, y + 1);
        }

        g.translate(-tx - 2, 0);

        if (border != null) {
            g.setColor(border.multiply(clr));
            g.drawRect(x, y, width - 1, height - 1);
        }
        g.setColor(clr);
        g.clearWorldClip();
        g.setClip(oldClip);
    }

    /**
     * Get the value in the text field
     *
     * @return The value in the text field
     */
    public String getText() {
        return value;
    }

    /**
     * Set the value to be displayed in the text field
     *
     * @param value The value to be displayed in the text field
     */
    public void setText(String value) {
        this.value = value;
        if (cursorPos > value.length()) {
            cursorPos = value.length();
        }
    }

    /**
     * Set the position of the cursor
     *
     * @param pos The new position of the cursor
     */
    public void setCursorPos(int pos) {
        cursorPos = pos;
        if (cursorPos > value.length()) {
            cursorPos = value.length();
        }
    }

    /**
     * Indicate whether the mouse cursor should be visible or not
     *
     * @param visibleCursor True if the mouse cursor should be visible
     */
    public void setCursorVisible(boolean visibleCursor) {
        this.visibleCursor = visibleCursor;
    }

    /**
     * Set the length of the allowed input
     *
     * @param length The length of the allowed input
     */
    public void setMaxLength(int length) {
        maxCharacter = length;
        if (value.length() > maxCharacter) {
            value = value.substring(0, maxCharacter);
        }
    }

    /**
     * Do the paste into the field, overrideable for custom behaviour
     *
     * @param text The text to be pasted in
     */
    protected void doPaste(String text) {
        recordOldPosition();

        for (int i = 0; i < text.length(); i++) {
            keyPressed(-1, text.charAt(i));
        }
    }

    /**
     * Record the old position and content
     */
    protected void recordOldPosition() {
        oldText = getText();
        oldCursorPos = cursorPos;
    }

    /**
     * Do the undo of the paste, overrideable for custom behaviour
     *
     * @param oldCursorPos before the paste
     * @param oldText      The text before the last paste
     */
    protected void doUndo(int oldCursorPos, String oldText) {
        if (oldText != null) {
            setText(oldText);
            setCursorPos(oldCursorPos);
        }
    }

    /**
     * @see org.newdawn.slick.gui.AbstractComponent#keyPressed(int, char)
     */
    public void keyPressed(int key, char c) {
        if (hasFocus()) {
            if (key != -1) {
                if ((key == Input.KEY_V) &&
                        ((input.isKeyDown(Input.KEY_LCONTROL)) || (input.isKeyDown(Input.KEY_RCONTROL)))) {
                    String text = Sys.getClipboard();
                    if (text != null) {
                        doPaste(text);
                    }
                    return;
                }
                if ((key == Input.KEY_Z) &&
                        ((input.isKeyDown(Input.KEY_LCONTROL)) || (input.isKeyDown(Input.KEY_RCONTROL)))) {
                    if (oldText != null) {
                        doUndo(oldCursorPos, oldText);
                    }
                    return;
                }

                // alt and control keys don't come through here   
                if (input.isKeyDown(Input.KEY_LCONTROL) || input.isKeyDown(Input.KEY_RCONTROL)) {
                    return;
                }
                if (input.isKeyDown(Input.KEY_LALT) || input.isKeyDown(Input.KEY_RALT)) {
                    return;
                }
            }

            if (lastKey != key) {
                lastKey = key;
                repeatTimer = System.currentTimeMillis() + INITIAL_KEY_REPEAT_INTERVAL;
            } else {
                repeatTimer = System.currentTimeMillis() + KEY_REPEAT_INTERVAL;
            }
            lastChar = c;

            if (key == Input.KEY_LEFT) {
                if (cursorPos > 0) {
                    cursorPos--;
                }
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            } else if (key == Input.KEY_RIGHT) {
                if (cursorPos < value.length()) {
                    cursorPos++;
                }
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            } else if (key == Input.KEY_BACK) {
                if ((cursorPos > 0) && (value.length() > 0)) {
                    if (cursorPos < value.length()) {
                        value = value.substring(0, cursorPos - 1)
                                + value.substring(cursorPos);
                    } else {
                        value = value.substring(0, cursorPos - 1);
                    }
                    cursorPos--;
                }
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            } else if (key == Input.KEY_DELETE) {
                if (value.length() > cursorPos) {
                    value = value.substring(0, cursorPos) + value.substring(cursorPos + 1);
                }
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            } else if ((c < 127) && (c > 31) && (value.length() < maxCharacter)) {
                if (cursorPos < value.length()) {
                    value = value.substring(0, cursorPos) + c
                            + value.substring(cursorPos);
                } else {
                    value = value.substring(0, cursorPos) + c;
                }
                cursorPos++;
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            } else if (key == Input.KEY_RETURN) {
                notifyListeners();
                // Nobody more will be notified   
                if (consume) {
                    gc.getInput().consumeEvent();
                }
            }

        }
    }

    /**
     * @see org.newdawn.slick.gui.AbstractComponent#setFocus(boolean)
     */
    public void setFocus(boolean focus) {
        lastKey = -1;
        super.setFocus(focus);
    }
}   


Author:  ac99 [ Tue May 01, 2012 7:16 pm ]
Post subject:  Re: Unable to create TextField

Awesome, that fixed my problem with the GUIContext thanks mortias!

Now I've run into another problem. When I went to test the textfield on an android device, when selected it doesn't open the virtual keyboard. How would I go about getting the virtual keyboard to show up on when the textfield is selected??

Author:  mortias [ Wed May 02, 2012 8:17 am ]
Post subject:  Re: Unable to create TextField

i think this is more native to android,

i didn't test it but found this as an example:

To show:

Code:
EditText editText = (EditText) findViewById(R.id.myEdit);
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

And to hide:
Code:
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/