2013-04-23 69 views
0

好吧,我有一個垂直字符串,但是當它包含I或L時,它們與字符串的其餘部分偏移,因爲它們的印刷方式如何,它們在某種意義上左對齊他們被繪製的盒子不像其他的被繪製居中。我想知道如何讓這些信件與其他信件一致。同樣重要的是,這些都是個別的抽繩調用。我嘗試使用AffineTransform,但它將所有字母混合在一起。這是我用來循環字符串並寫入每個字符的代碼。在java中垂直字符串中居中各個字母

for(int i =0; i<team.length();i++) 
{ 
    gg.drawString(Character.toString(team.charAt(i)), 100, ypos-fm.getDescent()); 
    ypos+=40; 
} 

如果您想測試它,我使用的字符串是BOLIVAR。提前致謝!

+0

請編輯您的問題以包含顯示您使用charWidth()的[sscce](http://sscce.org/)。 – trashgod 2013-04-23 02:26:35

+0

我不使用charWidth。 – staticFlow 2013-04-23 02:27:52

+0

你還會怎麼做? – trashgod 2013-04-23 02:40:04

回答

2

你可以嘗試爲中心周圍的字符文本寬度

enter image description here

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.FontMetrics; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class TestVerticalTexr { 

    public static void main(String[] args) { 
     new TestVerticalTexr(); 
    } 

    public TestVerticalTexr() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     public TestPane() { 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      String team = "BOLIVAR"; 
      FontMetrics fm = g2d.getFontMetrics(); 
      int ypos = fm.getHeight(); 
      for (int i = 0; i < team.length(); i++) { 
       int x = 100 - (fm.charWidth(team.charAt(i))/2); 
       g2d.drawString(Character.toString(team.charAt(i)), x, ypos); 
       ypos += fm.getHeight(); 
      } 
      g2d.dispose(); 
     } 
    } 
} 
+0

這是完美的!謝謝! – staticFlow 2013-04-23 02:42:50

1

你可以考慮使用一個Text Icon。在文字的繪畫中它更復雜一些。