Saturday 15 October 2016

Painting In Swing



·         Swing uses a bit more sophisticated approach to painting than AWT that involves three distinct methods: paintComponent(), paintBorder(), and paintChildren().
These methods paint the indicated portion of a component and divide the painting process into its three distinct, logical actions.
·         To paint to the surface of a swing component, we will create a subclass of the component and then override its paintComponent() method. This is the method that paints the interior of the component. We will not normally override the other two painting methods. When overriding paintComponent(), the first thing we must do is call super.paintComponent(), so that the superclass portion of the painting process takes place. The paintComponent method is shown here:
Protected void paintComponent(Graphics g).
                        The parameter g is the graphics context to which output is written.
·         To cause a component to be painted under program control, call repaint(). It works in Swing just as it does for the AWT. The repaint() method is defined by Component. Calling it causes the system to call paint() as soon as it is possible to do so. In Swing the call to paint() results in a call to paintComponent().
·         To obtain the border width, call getInsets(), as shown here:
Insets getInsets()
This method is defined by Container and overridden by JComponent. It returns an Insets object that contains the dimensions of the border. The inset values can be obtained by using these fields:
            int top;
            int bottom;
            int left;
            int right;
·         We can obtain the width and height of the component by calling getWidth() and getHeight() on the component.
int getWidth();
int getHeight();
By subtracting the value of insets, we can compute the usable width and height of the component.
·         Example:
SwingPaint:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPaint extends JPanel
{
  Insets ins; //Holds the Panel's Inset
  MyPaint()
  {
    setBorder(BorderFactory.createLineBorder(Color.RED,5));
  }
  protected void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    int x1,y1,x2,y2;
    //Obtain the height and width of the component
    int h=getHeight();
    int w=getWidth();
    ins=getInsets();
    x1=y1=0;
    x2=w-ins.left;
   y2=h-ins.bottom;
   g.drawLine(x1,y1,x2,y2);
   x1=y1=50;
   x2=y2=200;
   g.drawRect(x1,y1,x2,y2);
 }
}
class SwingPaint
{
 MyPaint pp;
 SwingPaint()
 {
  JFrame frm=new JFrame("My Swing Frame");
  frm.setSize(100,100);
  frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  pp=new MyPaint();
  frm.add(pp);
    frm.setVisible(true);
 }
 public static void main(String args[])
 {
  SwingUtilities.invokeLater(new Runnable(){
   public void run()
   {
    new SwingPaint();
   }
  });
 }
}

No comments:
Write comments