这正是我想要做的事情:
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 5));
g2.setPaint(Color.black);
g2.drawString("Line 1\nLine 2", x, y);
该行打印如下:
Line1Line2
我想这样:
Line1
Line2
我如何在drawString
中执行此操作?
除了如何为行做标签空间?
答案 0 :(得分:5)
private void drawString(Graphics g, String text, int x, int y) { for (String line : text.split("\n")) g.drawString(line, x, y += g.getFontMetrics().getHeight()); } private void drawtabString(Graphics g, String text, int x, int y) { for (String line : text.split("\t")) g.drawString(line, x += g.getFontMetrics().getHeight(), y); } Graphics2D g2 = (Graphics2D) g; g2.setFont(new Font("Serif", Font.PLAIN, 5)); g2.setPaint(Color.black); drawString(g2,"Line 1\nLine 2", 120, 120); drawtabString(g2,"Line 1\tLine 2", 130, 130);
答案 1 :(得分:0)
以下是我在JPanel
中使用标签扩展和多行绘制文字的代码段:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Scratch {
public static void main(String argv[]) {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paint(Graphics graphics) {
graphics.drawRect(100, 100, 1, 1);
String message =
"abc\tdef\n" +
"abcx\tdef\tghi\n" +
"xxxxxxxxdef\n" +
"xxxxxxxxxxxxxxxxghi\n";
int x = 100;
int y = 100;
FontMetrics fontMetrics = graphics.getFontMetrics();
Rectangle2D tabBounds = fontMetrics.getStringBounds(
"xxxxxxxx",
graphics);
int tabWidth = (int)tabBounds.getWidth();
String[] lines = message.split("\n");
for (String line : lines) {
int xColumn = x;
String[] columns = line.split("\t");
for (String column : columns) {
if (xColumn != x) {
// Align to tab stop.
xColumn += tabWidth - (xColumn-x) % tabWidth;
}
Rectangle2D columnBounds = fontMetrics.getStringBounds(
column,
graphics);
graphics.drawString(
column,
xColumn,
y + fontMetrics.getAscent());
xColumn += columnBounds.getWidth();
}
y += fontMetrics.getHeight();
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
};
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true); }
}
看起来Utilities.drawTabbedText()
很有希望,但我无法弄清楚它需要什么作为输入。