Search code examples
javahtmlplayn

Tripleplay Button: Dynamic text with proper alignment on an Image Button (say the text justified , centre)


I am creating a window with two image buttons (using TriplePlay in my playN game).

Now I need dynamic text on these buttons. But when I add buttons with images (setIcon), I am not able to add Text on it same time. Please check the following code block I use now.


Interface iface = new Interface(null);
pointer().setListener(iface.plistener);
Styles buttonStyles = Styles.none().add(Style.BACKGROUND.is(new NullBackground())).
    addSelected(Style.BACKGROUND.is(Background.solid(0xFFCCCCCC)));
Stylesheet rootSheet = Stylesheet.builder().add(Button.class, buttonStyles).create();
Root buttonroot = iface.createRoot(AxisLayout.horizontal().gap(150), rootSheet);
buttonroot.setSize(width_needed, height_needed);
buttonroot.addStyles(Styles.make(Style.BACKGROUND.is(new NullBackground())));
graphics().rootLayer().add(buttonroot.layer);
Button you = new Button().setIcon(buttonImage);
Button friend = new Button().setIcon(buttonImage);
buttonroot.add(you).add(friend);
buttonroot.layer.setTranslation(x_needed, y_needed);
Root nameroot = iface.createRoot(AxisLayout.horizontal().gap(300), rootSheet);
nameroot.setSize(width_needed, height_needed);
nameroot.addStyles(Styles.make(Style.BACKGROUND.is(new NullBackground())));
graphics().rootLayer().add(nameroot.layer);
name = new Label("YOU");// we need the dynamic string variable instead
friendName = new Label("FRIEND"); // we need the dynamic string variable instead
nameroot.add(name).add(friendName);
nameroot.layer.setTranslation(x_needed, y_needed);

here I have tried making a root then add button with images to it then making another root and add labels on it so that it will be show like text on the image buttons. But I know this is a bad way of doing it, and the alignment will not be according to what needed as it a dynamic text. Is there anyway to add a button, with image and a label on it?

Thanks in anticipation


Solution

  • Creating a button with text and an icon is trivial:

    Button button = new Button("Text").setIcon(iconImage);
    

    You can then change the text on the button any time you like, like so:

    button.text.update("New Text");
    

    If you want a button with a background image with text rendered over the background, then do the following:

    Button button = new Button("Text").
      addStyles(Background.is(Background.image(bgImage)));
    

    Note that you will need the latest TriplePlay code (from Github) to use the ImageBackground. The latest code also supports Flash-style "scale9" backgrounds:

    Button button = new Button("Text").
      addStyles(Background.is(Background.scale9(bgImage)));