2012-11-01 44 views
1

可能重複:
Problems with newline in Graphics2D.drawString打印行分隔符的圖像中

String eol =System.lineSeparator(); 
     String sampleText =epcURNText +eol+studentName+eol+DelayComments+eol+ArrivalMethodComments+eol; 
     System.out.println(sampleText); 
     Font font = new Font("Tahoma", Font.PLAIN, 11); 
     FontRenderContext frc = new FontRenderContext(null, true, true); 

     //get the height and width of the text 
     Rectangle2D bounds = font.getStringBounds(sampleText, frc); 
     int w = (int) bounds.getWidth(); 
     int h = (int) bounds.getHeight(); 

     //create a BufferedImage object 
     BufferedImage image = new BufferedImage(w, h, 
       BufferedImage.TYPE_INT_RGB); 

     //calling createGraphics() to get the Graphics2D 
     Graphics2D g = image.createGraphics(); 

     //set color and other parameters 
     g.setColor(Color.WHITE); 
     g.fillRect(0, 0, w, h); 
     g.setColor(Color.BLACK); 
     g.setFont(font); 

     g.drawString(sampleText, (float) bounds.getX(), 
       (float) -bounds.getY()); 

     //releasing resources 
     g.dispose(); 



     // define the format of print document 
     ByteArrayOutputStream os = new ByteArrayOutputStream(); 
     ImageIO.write(image, "gif", os); 
     File f = new File("MyFile.jpg"); 
     ImageIO.write(image, "JPEG", f); 

在上述代碼,我想在圖像內打印帶有換行符的字符串。然而,換行符被省略,因此我的文本是在一行內顯示的?有誰知道如何解決這個問題?

+0

請參閱http://stackoverflow.com/questions/4413132/problems-with-newline-in-graphics2d-drawstring –

回答

2

使用HTML格式在JLabel中呈現文本,如this answer中的LabelRenderTest源所示。

它提供的東西比換行符更好 - 樣式的車身寬度。更好的是,我們不需要手動計算在哪裏放置文本的換行符(這也可能會以不固定寬度的字體呈現)。