Show character in a grid in Java

Description

The following code shows how to show character in a grid.

Example


//from  w  w w . j  a  va  2  s.  com

import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    final int w = 20;
    final int side = 25;
    final int[][] grid = new int[50][w];

    JPanel panel = new JPanel() {
      public void paintComponent(Graphics g) {
        Font font = new Font("WingDings", Font.PLAIN, 14);
        g.setFont(font);
        int off = 0;
        for (int i = 0; i < 256 * 256; i++) {
          if (font.canDisplay((char) i)) {
            off++;
            grid[off / w][off % w] = i;
            int x = off % w * side;
            int y = (off / w) * side + side;
            g.drawString("" + (char) i, x, y);
          }
        }
      }
    };
    JFrame frame = new JFrame();
    panel.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Show character in a grid in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform