import java.awt.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class DialogueMenu extends TextBox implements Serializable { public static final int PORTRAIT_WIDTH = 200; public static final int PADDING = 20; public static final int TOP_PADDING = 10; public static final double LINE_SPACING = 1.5; public static final int FREQUENCY = 2; public BufferedImageWrapper PORTRAIT; public int currentFrame = 0; public int frameCounter = 0; public boolean isNarrator; public DialogueMenu(int y, int yHeight, Font font, BufferedImageWrapper portrait, boolean isNarrator) { super(y, GamePanel.GAME_WIDTH - PORTRAIT_WIDTH - PADDING*3, yHeight, 0, font, null, null); PORTRAIT = portrait; checkForNarrator(); this.isNarrator = isNarrator; } public void checkForNarrator() { if (isNarrator) { newX = PORTRAIT_WIDTH + PADDING*2; } else { newX = PADDING; } } public void drawCenteredTextBox(Graphics g, String text, Color backgroundColor, Color textColor) { text = text.substring(0, currentFrame); if (backgroundColor != null) { g.setColor(textColor); if (isNarrator) { g.drawImage(PORTRAIT.image, newX - PORTRAIT_WIDTH - PADDING, newY, PORTRAIT_WIDTH, yHeight, null); } else { g.drawImage(PORTRAIT.image, GamePanel.GAME_WIDTH - PORTRAIT_WIDTH - PADDING, newY, PORTRAIT_WIDTH, yHeight, null); } ((Graphics2D)g).setStroke(new BasicStroke(4f)); g.drawRect(newX, newY, xWidth, yHeight - 4); g.setColor(backgroundColor); g.fillRect(newX, newY, xWidth, yHeight - 4); } g.setColor(textColor); drawCenteredString(g, newY, newX, text); } public static void drawCenteredString(Graphics g, int y, int x, String text) { // split text by spaces String[] newText = text.split(" "); ArrayList lines = new ArrayList(); lines.add(""); // get font size FontMetrics metrics = g.getFontMetrics(); int currentLineWidth = 0, lastLineIndex = 0; for (String s: newText) { currentLineWidth += metrics.stringWidth(s + " "); if (currentLineWidth - metrics.stringWidth(" ") < (GamePanel.GAME_WIDTH - PORTRAIT_WIDTH - PADDING*5)) { lines.set(lastLineIndex, lines.get(lastLineIndex) + s + " "); } else { currentLineWidth = metrics.stringWidth(s); lines.add(s + " "); lastLineIndex ++; } } y += TOP_PADDING; // center y (half is above y value, half is below y value) for (String s: lines) { y += (metrics.getAscent() - metrics.getDescent()) * LINE_SPACING; // draw string g.drawString(s + "\n", x + PADDING, y); } } public boolean draw(Graphics g, String text, Color backgroundColor, Color textColor) { checkForNarrator(); if (frameCounter >= FREQUENCY) { frameCounter -= FREQUENCY; currentFrame += 1; } g.setFont(font); drawCenteredTextBox(g, text, backgroundColor, textColor); frameCounter++; if (currentFrame >= text.length()) { currentFrame = 0; return true; } else { return false; } } }