/**
* * Simple Java 2D Example
* *	@version 0.9  12/07/2001
* *	@author Pascal Vuylsteker, Rod Harris
*/

package comp6461.lab1;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;


public class HelloWorldFrame extends JFrame
{
	public static void main(String[] args)
	{
		HelloWorldFrame frame = new HelloWorldFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}

	public HelloWorldFrame()
	{
		setTitle("Hello World !! ");

		// calculate the size of the screen and centre the Frame

		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Dimension screenSize = toolkit.getScreenSize();

		int screenXSize = (int) screenSize.getWidth();
		int screenYSize = (int) screenSize.getHeight();

		int xSize = screenXSize / 2;
		int ySize = screenYSize / 2;

		int x1 = (screenXSize - xSize) / 2;
		int y1 = (screenYSize - ySize) / 2;

		setBounds(x1,y1,xSize,ySize);

		setResizable(false);

		String name = JOptionPane.showInputDialog("What is your Name");

		HelloPanel panel = new HelloPanel(name, xSize, ySize);

		Container contentPane = getContentPane();
		contentPane.add(panel);
	}
}

class HelloPanel extends JPanel
{
	private String displayString;
	private Font textFont = new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 30);
	private int xSize;
	private int ySize;

	public HelloPanel(String name, int xs, int ys)
	{
		displayString = "Bonjour " + name;
		xSize = xs;
		ySize = ys;

		setBackground(Color.cyan);
	}

	public void	paintComponent(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;

		int width = getTextWidth(g2d, textFont, displayString);

		int x1 = 2 * xSize / 3 - width;
		int y1 = 2 * ySize / 3;

		g.drawString(displayString, x1, y1);
	}

	/**
		Calculates how many pixels wide a string will be when drawn with the given font
		@param g2d The Graphics2D device used to draw the text
		@param f The font to use
		@param s The string to check
		@return The number of pixels that will be needed
	*/
	public int getTextWidth(Graphics2D g2d, Font f, String s)
	{
		g2d.setFont(f);
		FontRenderContext context = g2d.getFontRenderContext();
		Rectangle2D bounds = f.getStringBounds(s, context);
		return (int) bounds.getWidth();
	}
}



