前回はデータを格納する部分だけを作ったので、今回は簡単に表示する部分を作成した。ファイルを適当に読み込んで表示している。そしてキーイベントでのカーソルの移動が手抜き。以下ソース。表示用コンポーネントのプログラムとそのテスト用のプログラムを載せておく
import javax.swing.JComponent; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Point; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; public class HexEditor extends JComponent implements KeyListener{ private BinaryDocument document; private Point cursor; private static final String[] DATA_TABLE = new String[]{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; public HexEditor(){ this(new BinaryDocument()); } public HexEditor(BinaryDocument document){ this.document = document; cursor = new Point(0, 0); setFocusable(true); addKeyListener(this); } public void paintComponent(Graphics g){ g.setFont(new Font("Monospaced", Font.PLAIN, 16)); g.setColor(Color.BLACK); int row = getHeight() / 16; int column = 16; for(int y = 0; y < row; y++){ for(int x = 0; x < column; x++){ int index = (y * column) + x; byte data = document.get(index); byte high = (byte)((data >> 4) & 0x0F); byte low = (byte)(data & 0x0F); g.drawString(DATA_TABLE[high], x * 26 + 8, (y + 1) * 20); g.drawString(DATA_TABLE[low], (x * 26) + 8 + 8, (y + 1) * 20); } } g.setColor(new Color(0x6080CCFF, true)); g.fillRect(cursor.x * 26 + 6, cursor.y * 20 + 4, 22, 20); } public void keyPressed(KeyEvent e){ switch(e.getKeyCode()){ case KeyEvent.VK_UP: cursor.y--; break; case KeyEvent.VK_DOWN: cursor.y++; break; case KeyEvent.VK_LEFT: cursor.x--; break; case KeyEvent.VK_RIGHT: cursor.x++; break; default: break; } repaint(); } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} }
テスト用プログラム(エントリポイント)
import javax.swing.JFrame; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.IOException; public class Main{ public static void main(String[] args) throws IOException{ BinaryDocument document = new BinaryDocument(10); int index = 0; int n; byte[] data = new byte[1024]; BufferedInputStream in = new BufferedInputStream(new FileInputStream("./Main.java")); while((n = in.read(data, 0, 1024)) > 0){ for(int i = 0; i < n; i++){ document.set(data[i], index++); } } HexEditor editor = new HexEditor(document); JFrame frame = new JFrame(); frame.add(editor); frame.setSize(600, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }