60 lines
2.2 KiB
Java
60 lines
2.2 KiB
Java
|
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 DialogueMenu(int y, int yHeight, Font font) {
|
||
|
super(y, GamePanel.GAME_WIDTH, yHeight, 0, font, null, null);
|
||
|
newX = PORTRAIT_WIDTH + PADDING;
|
||
|
}
|
||
|
|
||
|
public void drawCenteredTextBox(Graphics g, String text, Color backgroundColor, Color textColor) {
|
||
|
if (backgroundColor != null) {
|
||
|
g.setColor(textColor);
|
||
|
// TODO: make drawn line widths consistent
|
||
|
((Graphics2D)g).setStroke(new BasicStroke(4f));
|
||
|
g.drawRect(newX, newY, xWidth, yHeight);
|
||
|
g.setColor(backgroundColor);
|
||
|
g.fillRect(newX, newY, xWidth, yHeight);
|
||
|
}
|
||
|
g.setColor(textColor);
|
||
|
drawCenteredString(g, y, newX, xWidth, text);
|
||
|
}
|
||
|
|
||
|
public static void drawCenteredString(Graphics g, int y, int x, String text) {
|
||
|
// split text by spaces
|
||
|
String[] newText = text.split(" ");
|
||
|
ArrayList<String> lines = new ArrayList<String>();
|
||
|
lines.add("");
|
||
|
// get font size
|
||
|
FontMetrics metrics = g.getFontMetrics();
|
||
|
int currentLineWidth = 0, lastLineIndex = 0;
|
||
|
for (String s: newText) {
|
||
|
currentLineWidth += metrics.stringWidth(s);
|
||
|
if (currentLineWidth < (GamePanel.GAME_WIDTH - PORTRAIT_WIDTH - PADDING*2)) {
|
||
|
lines.set(lastLineIndex, lines.get(lastLineIndex) + s);
|
||
|
} else {
|
||
|
currentLineWidth = metrics.stringWidth(s);
|
||
|
lines.add(s);
|
||
|
}
|
||
|
}
|
||
|
y -= PADDING;
|
||
|
// center y (half is above y value, half is below y value)
|
||
|
for (String s: lines) {
|
||
|
y -= (metrics.getAscent() - metrics.getDescent()) / 2;
|
||
|
// draw string
|
||
|
g.drawString(text, x, y);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void draw(Graphics g, String text, Color backgroundColor, Color textColor) {
|
||
|
g.setFont(font);
|
||
|
drawCenteredTextBox(g, text, backgroundColor, textColor);
|
||
|
}
|
||
|
}
|