Credits

Tuesday, March 16, 2010

Creating Java Graphics Instance

We can create an instance of Graphics class outside our paint method. We can do this by using the line below:

Graphics yourObject = getGraphics();


With this command, we can now use Graphic methods the same way we use them inside paint.


See sample program to illustrate this. 



[+/-] show/hide



import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GraphicsDemoCreateObject extends Applet implements ActionListener{
String companyName = new String (" S T I");
JButton moveButton = new JButton ("Move it.");
Color newColor = new Color(100,20,255);//creating your own color
Font hell2Font = new Font ("Helvetica", Font.ITALIC, 12);
int x = 10, y = 50;

public void init()
{
setBackground(Color.yellow);
add(moveButton);

moveButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
Graphics gr = getGraphics();
gr.setFont(hell2Font);
gr.setColor(newColor);
gr.drawString(companyName,x+=20,y+=20);
//the condition below is to control the movement within applet page size
if (y>getSize().height)
moveButton.setEnabled(false);
}
}

AddThis