// MessagePanel.java: Display a message on a JPanel
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class MessagePanel extends JPanel
{
  private String message = "Welcome to Java"; // Message to display

  // (x, y) coordinates where the message is displayed
  private int xCoordinate = 20;
  private int yCoordinate = 20;

  // Indicating whether the message is displayed in the center
  private boolean centered;

  /**Default constructor*/
  public MessagePanel()
  {
  }

  /**Constructor with a message parameter*/
  public MessagePanel(String message)
  {
    this.message = message;
  }

  /**Getter method for message*/
  public String getMessage()
  {
    return message;
  }

  /**Setter method for message*/
  public void setMessage(String message)
  {
    this.message = message;
  }

  /**Getter method for xCoordinator*/
  public int getXCoordinate()
  {
    return xCoordinate;
  }

  /**Setter method for xCoordinator*/
  public void setXCoordinate(int x)
  {
    this.xCoordinate = x;
  }

  /**Getter method for yCoordinator*/
  public int getYCoordinate()
  {
    return yCoordinate;
  }

  /**Setter method for yCoordinator*/
  public void setYCoordinate(int y)
  {
    this.yCoordinate = y;
  }

  /**Getter method for centered*/
  public boolean isCentered()
  {
    return centered;
  }

  /**Setter method for centered*/
  public void setCentered(boolean centered)
  {
    this.centered = centered;
  }

  /**Paint the message*/
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);

    if (centered)
    {
      // Get font metrics for the current font
      FontMetrics fm = g.getFontMetrics();

      // Find the center location to display
      int w = fm.stringWidth(message);  // Get the string width
      // Get the string height, from top to the baseline
      int h = fm.getAscent();
      xCoordinate = getWidth()/2-w/2;
      yCoordinate = getHeight()/2+h/2;
    }

    g.drawString(message, xCoordinate, yCoordinate);
  }

  /**Override getter method for preferredSize*/
  public Dimension getPreferredSize()
  {
    return new Dimension(200, 100);
  }

  /**Override getter method for minimumSize*/
  public Dimension getMinimumSize()
  {
    return new Dimension(200, 100);
  }

  /**Main method to test MessagePanel*/
  public static void main(String[] args)
  {
    JFrame frame = new JFrame("Test MessagePanel");
    frame.setSize(200, 200);
    frame.getContentPane().add(new MessagePanel());
    frame.setVisible(true);
  }
}