从抽绳中心文本

时间:2014-04-21 08:13:29

标签: java user-interface drawstring

Soo用户可以选择是否选择文本"欢迎使用Java编程"文本在面板中应为斜体,粗体或居中。这些选项是复选框。我不确定如何制作它,以便当用户选择中心时,它将位于中心。

public void paint(Graphics g) {
   super.paint(g);
   g.setColor(Color.black);
   g.drawRoundRect(75,90,324,120,10,10);
   g.drawLine(183,90,183,210);
   g.setColor(currentC);
   g.setFont(new Font(currentFont, intBold + intItalic, 24));
   g.drawString("Welcome to Java Programming",30,70);
}

public void itemStateChanged(ItemEvent e) {
  if(e.getSource() == checkBoxBold) { 
      if(e.getStateChange() == ItemEvent.SELECTED)
          intBold = Font.BOLD;
      if(e.getStateChange() == ItemEvent.DESELECTED)
          intBold = Font.PLAIN;
  } 
  if(e.getSource() == checkBoxItalics) {
      if(e.getStateChange() == ItemEvent.SELECTED)
          intItalic = Font.ITALIC;
      if(e.getStateChange() == ItemEvent.DESELECTED)
          intItalic = Font.PLAIN;
  }  
  if(e.getSource() == checkBoxCenter) {
      if(e.getStateChange() == ItemEvent.SELECTED)
         //PROBLEM RIGHT HERE
      if(e.getStateChange() == ItemEvent.DESELECTED)

  } 
  if(e.getSource() == radioRed)
      currentC = Color.red;
  else if(e.getSource() == radioGreen)
      currentC = Color.green;
      else if(e.getSource() == radioBlue)
          currentC = Color.blue;
  if(e.getSource() == fontChoice)
      currentFont = fontNames[fontChoice.getSelectedIndex()];
  repaint();
}

1 个答案:

答案 0 :(得分:3)

使用 FontMetrics

FontMetrics fm = g.getFontMetrics();

要获得文字的宽度:

fm.stringWidth(text)

然后在

输出你的文字
width / 2 - fm.stringWidth(text) / 2

其中 width 是输出区域的宽度。