2013-04-23 67 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。在文字的绘画中它更复杂一些。