문제

Soo the user is given the choice to choose whether the text "Welcome to Java Programming" text should be italic, bold, or centered in the panel. These choices are check boxes. I'm not sure how to make it so that when the user picks center, it'll be in the center.

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();
}
도움이 되었습니까?

해결책

Use FontMetrics:

FontMetrics fm = g.getFontMetrics();

To get width of your text use:

fm.stringWidth(text)

Then output your text at

width / 2 - fm.stringWidth(text) / 2

Where width is a width of your output area.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top