Java Graphics How to - Display random string








Question

We would like to know how to display random string.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
//from   ww w .  j a  v a 2s .c  o m
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setContentPane(new StringPanel());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}
class StringPanel extends JPanel {
  static final int D_H = 500;
  static final int D_W = 500;
  int x = 50;
  int y = 50;

  List<String> list = new ArrayList<>();
  Random random = new Random(System.currentTimeMillis());

  String word;

  Font font = new Font("impact", Font.PLAIN, 28);
  int wordWidth;
  int wordHeight;

  public StringPanel() {
    for (int i = 1; i <= 100; i++) {
      list.add("Word " + i);
    }

    word = list.get(0);

    Timer timer = new Timer(500, e -> {
      int rand = random.nextInt(list.size());
      word = list.get(rand);
      x = random.nextInt(D_W - wordWidth);
      y = random.nextInt(D_H) + wordHeight;

      repaint();
    });
    timer.start();
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    FontMetrics fm = g.getFontMetrics(font);
    wordWidth = fm.stringWidth(word);
    wordHeight = fm.getAscent();

    g.setFont(new Font("impact", Font.PLAIN, 28));
    g.setColor(Color.BLUE);
    g.drawString(word, x, y);
  }

  @Override
  public Dimension getPreferredSize() {
    return new Dimension(D_H, D_W);

  }
}