Java 如何在图像上添加文本时添加高度元素
我想知道我们是否可以在给定的空间中添加高度元素 所以我可以具体说明Java 如何在图像上添加文本时添加高度元素,java,image,text,graphics,awt,Java,Image,Text,Graphics,Awt,我想知道我们是否可以在给定的空间中添加高度元素 所以我可以具体说明 public void drawString(Graphics g, String s, int x, int y, int width,int height) 现在,如果我的文本超过高度,它将与下一个文本重叠。我没有测试,但这可能会帮助您解决问题 public void drawString(Graphics g, String s, int x, int y, int width, int height) { //
public void drawString(Graphics g, String s, int x, int y, int width,int height)
现在,如果我的文本超过高度,它将与下一个文本重叠。我没有测试,但这可能会帮助您解决问题
public void drawString(Graphics g, String s, int x, int y, int width, int height) {
// FontMetrics gives us information about the width,
// height, etc. of the current Graphics object's Font.
FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight();
int curX = x;
int curY = y;
int totalHeight = 0;
String[] words = s.split(" ");
String word = "";
// end of words array wasn't reached and still some space left
for(int i = 0; i < words.length && totalHeight <= height; i++) {
// Find out thw width of the word.
int wordWidth = fm.stringWidth(word + " ");
// If text exceeds the width, then move to next line.
if (curX + wordWidth >= x + width) {
curY += lineHeight;
totalHeight += lineHeight;
curX = x;
}
g.drawString(word, curX, curY);
// Move over to the right for next word.
curX += wordWidth;
}
}
你们想做什么?你们想画一条占据多行的线吗?我正在画一条占据多行的线。但如果最后一行超过指定的高度,我想限制字符串。一种方法是在JLabel中使用HTML格式&将所需的宽度设置为样式。有关示例,请参见源代码。设置宽度和字符串后,标签应能够报告首选尺寸,包括高度。