2014-10-04 4 views
1

Я хочу использовать TextButton для моих пользовательских кнопок, но это требует от меня (re) поместить text или Label в пределах этого TextButton. Я пробовал некоторые варианты, но я довольно застрял.Позиционная метка в TextButton?

//this seems straightforward but nothing changes. 
final TextButton b = new TextButton("LABEL", skin); 
b.getLabel().setPosition(100, -20); 

//Read somewhere about adding new children to buttons but no success either. 
final TextButton b = new TextButton("OLD LABEL", skin); 
b.clearChildren(); 
Label l = new Label("NEW LABEL", skin); 
l.setPosition(400, 600); 
b.add(l); 

b.layout(); // Does not help either. 

Я добавив Button прямо в Stage без стола для того, что это имеет значение. У кого-нибудь есть идеи по этому поводу?

enter image description here

+0

Кнопка является таблица подкласса. Вместо того, чтобы пытаться напрямую переместить внутреннюю метку, просто вызовите 'textButton.top(). Right(). PadTop (20) .padRight (20);'. Если это не сработает, возможно, поможет 9-патч. – Tenfour04

+0

Если вам нужна прямоугольная область для расширения до различных размеров в зависимости от строки, посмотрите на использование 9-патча для фона. На самом деле, только 9-патч может решить эту проблему. В пользовательском интерфейсе Android 9-патч может определять, какая часть изображения выходит за пределы области, куда будет идти текст. Не уверен, что он ведет себя одинаково в Libgdx. – Tenfour04

+0

Посмотрите здесь: http://javagamexyz.blogspot.de/2013/05/user-interface-menus-with-scene2dui-and.html, вероятно, вы можете найти что-то полезное. Этот метод может быть полезен для вас в коде src на этой странице: public void addButton (String label, String secondaryLabel, ListListener, boolean active) .... Мне удалось получить правильную позицию метки [как x, так и y], I может при необходимости отправить текст кода ... – dawez

ответ

0

texbutton это кнопка, к которой они добавили метку в конструктор,

label = new Label(text, new LabelStyle(style.font, style.fontColor)); 
     label.setAlignment(Align.top); 
     add(label).expand().fill(); 

первое, что есть, или не видят какой-либо метод, чтобы изменить выравнивание метки ,

label.setAlignment(Align.top); 

с другой стороны на этикетке была добавлена ​​в новую соту, актер,

add(label).expand().fill(); 

зная, что единственное, что мне пришло в голову было реализовать некоторые дома остались, как я показать, не очень хорошо, но я думаю, что вы будете

import com.badlogic.gdx.Gdx; 
import com.badlogic.gdx.graphics.Color; 
import com.badlogic.gdx.graphics.g2d.Batch; 
import com.badlogic.gdx.graphics.g2d.BitmapFont; 

import com.badlogic.gdx.scenes.scene2d.ui.Button; 
import com.badlogic.gdx.scenes.scene2d.ui.Label; 
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; 
import com.badlogic.gdx.scenes.scene2d.ui.Skin; 
import com.badlogic.gdx.scenes.scene2d.utils.Align; 
import com.badlogic.gdx.scenes.scene2d.utils.Drawable; 
import com.esotericsoftware.tablelayout.Cell; 


public class LabelButton extends Button { 

    private final Label label; 
    private TextButtonStyle style; 
    private float widthButton, heightButton; 

    public LabelButton (String text, Skin skin) { 
     this(text, skin.get(TextButtonStyle.class)); 
     setSkin(skin); 
    } 
    //NEW CODE1 FOR ADD, NEW CLASS EXTENDS BUTTON, OTHER CODE EQUALS TEXTBUTTON. 
    /** @param boolean alignament: false desactiva la alineación al centro, x e y son las coordenadas donde se mostrar el texto del label. 
     * <p> 
     * xLabel, e yLabel tienen su pivote en el centro del texto, asi que las posiciones son basadas respecto a esto. 
     * <p> 
     * las variables float widthButton, y float heightButton, referidos a el boton. 
     * <p> 
     * boolean alignament: false deactivate center alignment, x and y are the coordinates where show the text label. 
     * <p> 
     * xLabel, ylabel and have its pivot in the center of the text, so the positions are based on this. 
     * <p> 
     * las variables widthButton float and float heightButton, referring to the button 
     */ 

    public LabelButton (String text, Skin skin, boolean alignament, float xLabel, float yLabel, float widthButton, float heightButton) { 
     this(text, skin.get(TextButtonStyle.class), alignament, xLabel, yLabel, widthButton, heightButton); 
     setSkin(skin); 
    } 
    //END NEW CODE1 

    public LabelButton (String text, Skin skin, String styleName) { 
     this(text, skin.get(styleName, TextButtonStyle.class)); 
     setSkin(skin); 
    } 

    public LabelButton (String text, TextButtonStyle style) { 
     super(); 
     setStyle(style); 
     this.style = style; 
     label = new Label(text, new LabelStyle(style.font, style.fontColor)); 
     label.setAlignment(Align.top); 
     add(label).expand().fill(); 
     setSize(getPrefWidth(), getPrefHeight()); 
    } 
    //NEW CODE2 FOR ADD, NEW CLASS EXTENDS BUTTON, OTHER CODE EQUALS TEXTBUTTON. 
    /** @param boolean alignament: false desactiva la alineación al centro, x e y son las coordenadas donde se mostrar el texto del label. 
     * <p> 
     * xLabel, e yLabel tienen su pivote en el centro del texto, asi que las posiciones son basadas respecto a esto. 
     * <p> 
     * las variables float widthButton, y float heightButton, referidos a el boton. 
     * <p> 
     * boolean alignament: false deactivate center alignment, x and y are the coordinates where show the text label. 
     * <p> 
     * xLabel, ylabel and have its pivot in the center of the text, so the positions are based on this. 
     * <p> 
     * las variables widthButton float and float heightButton, referring to the button 
     */ 

    public LabelButton (String text, TextButtonStyle style, boolean alignament, float xLabel, float yLabel, float widthButton, float heightButton) { 
     super(); 
     setStyle(style); 
     this.style = style; 
     label = new Label(text, new LabelStyle(style.font, style.fontColor)); 
     if (alignament == true){ 
      label.setAlignment(Align.top); 
      add(label).expand().fill(); 
     }else{ 
      this.heightButton = heightButton; 
      this.widthButton = widthButton; 
      add(label).padRight(widthButton - (xLabel * 2)).padBottom(-heightButton + (yLabel * 2));   
     } 

     setSize(getPrefWidth(), getPrefHeight()); 

    } 

    public void setCoordenadasLabel(float xLabel, float yLabel){ 
     getCell(label).padRight(widthButton - (xLabel * 2)).padBottom(-heightButton + (yLabel * 2)); 
    } 
    //END NEW CODE2 

    public void setStyle (ButtonStyle style) { 
     if (style == null) { 
      throw new NullPointerException("style cannot be null"); 
     } 
     if (!(style instanceof TextButtonStyle)) throw new IllegalArgumentException("style must be a TextButtonStyle."); 
     super.setStyle(style); 
     this.style = (TextButtonStyle)style; 
     if (label != null) { 
      TextButtonStyle textButtonStyle = (TextButtonStyle)style; 
      LabelStyle labelStyle = label.getStyle(); 
      labelStyle.font = textButtonStyle.font; 
      labelStyle.fontColor = textButtonStyle.fontColor; 
      label.setStyle(labelStyle); 
     } 
    } 

    public TextButtonStyle getStyle() { 
     return style; 
    } 

    public void draw (Batch batch, float parentAlpha) { 
     Color fontColor; 
     if (isDisabled() && style.disabledFontColor != null) 
      fontColor = style.disabledFontColor; 
     else if (isPressed() && style.downFontColor != null) 
      fontColor = style.downFontColor; 
     else if (isChecked() && style.checkedFontColor != null) 
      fontColor = (isOver() && style.checkedOverFontColor != null) ? style.checkedOverFontColor : style.checkedFontColor; 
     else if (isOver() && style.overFontColor != null) 
      fontColor = style.overFontColor; 
     else 
      fontColor = style.fontColor; 
     if (fontColor != null) label.getStyle().fontColor = fontColor; 
     super.draw(batch, parentAlpha); 
    } 

    public Label getLabel() { 
     return label; 
    } 

    public Cell getLabelCell() { 
     return getCell(label); 
    } 

    public void setText (String text) { 
     label.setText(text); 
    } 

    public CharSequence getText() { 
     return label.getText(); 
    } 

    /** The style for a text button, see {@link TextButton}. 
    * @author Nathan Sweet */ 
    static public class TextButtonStyle extends ButtonStyle { 
     public BitmapFont font; 
     /** Optional. */ 
     public Color fontColor, downFontColor, overFontColor, checkedFontColor, checkedOverFontColor, disabledFontColor; 

     public TextButtonStyle() { 
     } 

     public TextButtonStyle (Drawable up, Drawable down, Drawable checked, BitmapFont font) { 
      super(up, down, checked); 
      this.font = font; 
     } 

     public TextButtonStyle (TextButtonStyle style) { 
      super(style); 
      this.font = style.font; 
      if (style.fontColor != null) this.fontColor = new Color(style.fontColor); 
      if (style.downFontColor != null) this.downFontColor = new Color(style.downFontColor); 
      if (style.overFontColor != null) this.overFontColor = new Color(style.overFontColor); 
      if (style.checkedFontColor != null) this.checkedFontColor = new Color(style.checkedFontColor); 
      if (style.checkedOverFontColor != null) this.checkedFontColor = new Color(style.checkedOverFontColor); 
      if (style.disabledFontColor != null) this.disabledFontColor = new Color(style.disabledFontColor); 
     } 
    } 
} 

это новые методы использования в том, что вы хотите.

public LabelButton (String text, TextButtonStyle style, boolean alignament, float xLabel, float yLabel, float widthButton, float heightButton) { 
     super(); 
     setStyle(style); 
     this.style = style; 
     label = new Label(text, new LabelStyle(style.font, style.fontColor)); 
     if (alignament == true){ 
      label.setAlignment(Align.top); 
     }else{ 
      this.heightButton = heightButton; 
      this.widthButton = widthButton; 
     } 

     add(label).padRight(widthButton - (xLabel * 2)).padBottom(-heightButton + (yLabel * 2)); 
     setSize(getPrefWidth(), getPrefHeight()); 
    } 

    public void setCoordenadasLabel(float xLabel, float yLabel){ 
     getCell(label).padRight(widthButton - (xLabel * 2)).padBottom(-heightButton + (yLabel * 2)); 
    } 

простой пример

.//

LabelBoton labelBoton = new LabelButton("hola", skinMenuPrincipal, false, 150, 150, 300, 300); 
labelBoton.setBounds(50, 50, 300, 300); 

stage.addActor(labelBoton); 

в конструкторе, он по-прежнему такой же, как и раньше, но использовать логический ложь, что не совпадает с центром, то первые два поплавка - это то место, где вы хотите, чтобы текст появлялся, но ось была центром этого одного угла, а последние два поплавка

вы должны сказать, что высота и ширина вы будете иметь кнопку в orde r для выполнения вычислений, то не используйте setPosition, чтобы метка находилась в ячейке, и я ее не делаю, поэтому я управлял тем, что разрешало мне ячейку, затем делайте setBounds с одинаковой высотой и шириной

Этот другой метод позволяет переместить метку, а не изменять высоту и ширину кнопки вы создали

setCoordenadasLabel(float xLabel, float yLabel); 

также сказать вам, кто не на точность 100%, но я думаю, что вы будете стоит для одного стороне, то вы должны открыть файл uiskin.json и добавить это

com.mygdx.game.LabelButton$TextButtonStyle: { 
default: { down: default-round-down, up: default-round, font: default-font, fontColor: white }, 
toggle: { down: default-round-down, up: default-round, checked: default-round-down, font: default-font, fontColor: white, downFontColor: red } 
}, 

com.mygdx.game заменен. по названию нового пакета, в котором этот класс

Я надеюсь, что вы работаете и будете тем, кем хотите, и я докажу, что это работает, но нет, если появится какая-то ошибка, извините за мой английский, если я не выражу ясно, пока.

другой способ

другой способ заключается в использовании только без расширения класса, но и для различных кнопок, и если вы должны изменяться во время применения или более по точности, я думаю, что лучше использовать расширенный класс.

TEXTBUTTON.getCell(label).padRight("YOUR POSITION").padBottom("YOUR POSITION); 
+0

Мне просто нужно иметь возможность перемещать текст внутри кнопки. Скажем, моя большая кнопка - 300x200, мой текст/ярлык - всего 120x40, нужно аккуратно позиционировать в левом верхнем углу с точностью до пикселя. – Madmenyo

+0

Мне все равно, о столе, с или без. Мне совершенно удобно создавать таблицы, меню и пользовательские интерфейсы. Мне просто нужно переместить текст внутри текстового элемента. – Madmenyo

+0

Я добавил изображение, которое поможет вам понять. – Madmenyo

0

Решение легко:

final TextButton b = new TextButton("LABEL", skin); 
b.getLabelCell().padBottom(xxx); 
Смежные вопросы