【问题标题】:converting char to string and then inserting it into a JLabel [duplicate]将字符转换为字符串,然后将其插入 JLabel [重复]
【发布时间】:2016-02-16 22:34:00
【问题描述】:
public class Tile extends JLabel{

private char _c;
static char randomChar;

public Tile(char c, Color background) {
    super();
    setBackground(background);
    setOpaque(true);
    _c = c;

}

public static char randomLetter() {
    Random r = new Random();
    randomChar = (char) (97 + r.nextInt(25));
    return randomChar;
    }

public static char getChar(){
    return Tile.randomLetter();
}

public static String convert(){
    char ch = Tile.randomLetter();
    return String.valueOf(ch);


}

public static void main(String[] args) {
    Tile tile = new Tile(Tile.convert(), Color.BLUE);
    Tile tile1 = new Tile(Tile.randomLetter(), Color.RED);
    Tile tile2 = new Tile(Tile.randomLetter(), Color.GREEN);
    Tile tile3 = new Tile(Tile.randomLetter(), Color.YELLOW);

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new GridLayout(4,1));
    frame.setSize(500, 800);
    frame.setVisible(true);
    frame.add(tile);
    frame.add(tile1);
    frame.add(tile2);
    frame.add(tile3);

    System.out.println(Tile.convert());

所以我试图制作一个有四个图块的游戏,并且我使用 Jlabels 作为我的图块。我的图块接受一个字符和一种颜色,并且由于 jlabels 不接受字符,我试图制作一种方法将我的字符转换为字符串,然后将它放在我的 jlabel 中,以便它接受它。我该怎么做?

【问题讨论】:

  • String.valueOf(char)
  • 我已经以社区 wiki 的身份回答了这个问题,因为我不想为这个答案提供代表。编辑:另外,发现重复的问题和答案并用于关闭此问题。

标签: java


【解决方案1】:

假设一个名为myChar的char变量,那么简单

String text = "" + myChar;

// or

String text2 = String.valueOf(myChar);

会起作用的。

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 2023-02-01
    • 1970-01-01
    • 2017-09-29
    • 2016-12-11
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多