如何将drawString居中?

时间:2015-05-13 03:25:11

标签: java string swing

有没有办法自动居中绘制的字符串而不用手工制作?或者你每次都必须手动完成吗?

1 个答案:

答案 0 :(得分:3)

由于这是一个Swing GUI,我建议您让GUI为您进行居中 - 将文本放入JLabel,其水平对齐设置为SwingConstants.CENTER,并且将JLabel置于中心位置,例如在BorderLayout.PAGE_START位置的BorderLayout使用容器中,以及bingo,您的文本居中。

例如,以下代码显示为:
enter image description here

import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.*;

public class CenteredText extends JPanel {
   private static final String TOP_TEXT = "Top Text";
   private static final String CENTER_TEXT = "Center Text";
   private static final String BOTTOM_TEXT = "Bottom Text";
   public CenteredText() {
      JLabel topLabel = new JLabel(TOP_TEXT, SwingConstants.CENTER);
      topLabel.setFont(topLabel.getFont().deriveFont(Font.BOLD, 20f));

      JLabel centerLabel = new JLabel(CENTER_TEXT, SwingConstants.CENTER);
      centerLabel.setFont(centerLabel.getFont().deriveFont(Font.BOLD, 80f));
      int ebGap = 20;
      centerLabel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));

      JLabel bottomLabel = new JLabel(BOTTOM_TEXT, SwingConstants.CENTER);
      bottomLabel.setFont(bottomLabel.getFont().deriveFont(Font.PLAIN, 8f));

      setLayout(new BorderLayout());
      add(topLabel, BorderLayout.PAGE_START);
      add(centerLabel, BorderLayout.CENTER);
      add(bottomLabel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      CenteredText mainPanel = new CenteredText();

      JFrame frame = new JFrame("CenteredText");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}