Call paint or validate

What should I call paint or validate once a person
minimizes or maximizes a frame or a dialog box.
I have little confusion on this.
rajesh

paint is to render, validate is for layout stuff. Sometimes the UI becomes dirty even if the layout did not change. If your UI seems to be painted but display a bad layout, call validate. Note that you also might have to call both, empiric testing will prevail in this domain since Containers are sometimes a bit strange on their behaviours.
Also, do not use paint but rather repaint(), it would be better. Also note that there's an invalidate method, depending on what you are doing, invalidate might be your answer.
conclusion:
use repaint(), invalidate(), validate(). the use of 3, 2 or 1 of those methods will be answered by empiric tests.

Similar Messages

  • How to call paint() method during creating object

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         Oval(float width) {
              this.width = width;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
              repaint();
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
              int i = 10;
              super.paint(g);
                   g.setColor(Color.blue);
                   g.drawOval(90, 0+i, 90, 90);
                   System.out.println("paint()");
    public class FinalVersionFactory {
        JFrame f = new JFrame();
        Container cp = f.getContentPane();
        float width = 0;
        SomeShape getShape() {
             return new Oval(width++); //I want to paint this oval when I call getShape() method
         public FinalVersionFactory() {
              f.setSize(400, 400);
    //          cp.add(new Oval()); without adding
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        getShape();
              f.setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I need help. When I cliked on the JFrame nothing happened. I want to call paint() method and paint Oval when I create new Oval() object in getShape(). Can you correct my mistakes? I tried everything...Thank you.

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class SomeShape extends JPanel {
         protected static float width;
         protected static BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
    class Oval extends SomeShape {
         static int x, y;
         Oval(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(Color.blue);
                   pen.setStroke(line);
                   g.drawOval(x, y, 90, 90);
                   System.out.println("Oval.paint()"+"x="+x+"y="+y);
    class Rect extends SomeShape {
         static int x, y;
         Rect(float width, int x, int y) {
              this.width = width;
              this.x = x;
              this.y = y;
              line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
         public void paint(Graphics g) {
              Graphics2D pen = (Graphics2D)g;
                   g.setColor(new Color(250, 20, 200, 255));      
                   pen.setStroke(line);
                   g.drawRect(x, y, 80, 80);
                   System.out.println("Rect.paint()"+"x="+x+"y="+y);
    public class FinalVersionFactory extends JFrame {
        Container cp = getContentPane();
        float width = 0;
        int x = 0;
        int y = 0;
            boolean rect = false;
        SomeShape getShape() {
             SomeShape s;
              if(rect) {
                   s = new Rect(width, x, y);
                   System.out.println("boolean="+rect);
              } else {
                   s = new Oval(width++, x, y);
                   System.out.println("boolean="+rect);
              System.out.println("!!!"+s); //print Oval or Rect OK
              return s; //return Oval or Rect OK
         public FinalVersionFactory() {
              setSize(400, 400);
              SomeShape shape = getShape();
              cp.add(shape); //First object which is add to Container(Oval or Rect), returned by getShape() method
              //will be paint all the time. Why? Whats wrong?
              cp.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent e) {
                        x = e.getX();
                        y = e.getY();
                        rect = !rect;
                        getShape();
                        cp.repaint(); //getShape() return Oval or Rect object
                                      //but repaint() woks only for object which was added(line 67) as first
              setVisible(true);
         public static void main(String[] args) { new FinalVersionFactory(); }
    }I almost finish my program but I have last problem. I explained it in comment. Please look at it and correct my mistakes. I will be very greatful!!!
    PS: Do you thing that this program is good example of adoption Factory Pattern?

  • Calling paint(g) on components

    When can you call paint(g) on a component? Does it have to be on screen for it to have any effect? ie if I call paint(g) on a component when it is not visible will it have any effect on the g I pass to it? (g is a Graphics instance.)

    Hi,
    that actually depends on the component. JComponent for example first checks whether its size has width and height greater that zero. Unless it doesn't paint. And this may happen if you don't set the size manually if its not on screen.
    Other components may have some check if they're visible or something.
    However this depends on the component in question.
    Michael

  • Correct clipping when calling "paint()" from thread

    How do I achieve correct clipping around JMenus or JTooltips when calling paint() for a Component from a background thread?
    The whole story:
    Trying to implement some blinking GUI symbols (visualizing alerts), I implemented a subclass of JPanel which is linked to a Swing timer and thus receives periodic calls to its "actionPerformed()" methods.
    In the "actionPerformed()" method, the symbol's state is toggled and and repainting the object should be triggered.
    Unfortunately, "repaint()" has huge overhead (part of the background would need to be repainted, too) and I decided to call "paint( getGraphics() )" instead of it.
    This works fine as long as there is nothing (like a JMenu, a JComboBox or a JTooltip) hiding the symbol (partially or completely). In such case the call to paint() simply "overpaints" the object.
    I suppose setting a clipping region would help, but where from can I get it?
    Any help welcome! (I alread spent hours in search of a solution, but I still have no idea...)

    For all those interested in the topic:
    It seems as if there is no reliable way to do proper clipping when calling
    "paint()".
    The problem was that when my sub-component called "repaint()" for itself, the underlying component's "paintComponent()" method was called as well. Painting of that component was complex and avoiding complexity by restricting
    on the clipping region is not easily possible.
    I have several sub-components to be repainted regularly, resulting in lots of calls to my parent component's "paintComponent()" method. This makes the
    repainting of the sub-components awfully slow; the user can see each one begin painted!
    Finally I decided I had to speed up the update of the parent component. I found two possible solutions:
    a) Store the background of each of the sub-components in a BufferedImage:
    When "paintComponent()" is called: test, if the clipping rectangle solely
    contains the region of a sub-component. If this is true check if there
    is a "cached" BufferedImage for this region. If not, create one, filling
    it with the "real" "paintComponent()" method using the Graphic object of
    the BufferedImage. Once we have such a cached image, simply copy it the
    the screen (i.e. the Graphics object passed as method parameter).
    b) To avoid the handling of several of such "cached" image tiles, simply
    store the whole parent component's visible part ("computeVisibleRect()")
    in a BufferedImage. Take care to re-allocate/re-paint this image each
    time the visible part changes. (I need to restrict the image buffer to
    the visible part since I use a zooming feature: Storing the whole image
    would easily eat up all RAM!) In the "paintComponent()", simple check
    if the currently buffered image is still valid - repaint if not -
    and copy the requested part of it (clip rect) to the screen. That's it!
    The whole procedure works fine.
    Best regards,
    Armin

  • How to call paint ( )?

    Hi,
    I am trying to display a tring but I dont know how to call paint ( ). I used show but its giving me mesg that show is deprecated.
    Can somebody help me in this regard?
    import java.awt.*;
    class DisplayText extends Frame{
    DisplayText (String s) {
      super(s);
    public void paint (Graphics g) {
      g.drawString("Hello World", 10,10);
    public static void main (String args[ ]) {
       DisplayText screen = new DisplayText("Example 1");
                screen.setSize(500,100);
                screen.setVisible(true);
    }Zulfi.

    I don't really recommend using the paint() methodfor
    drawing Strings on the Frame. Paint should be used
    just for Graphics
    So how do you make a component show a text? Use a Label :-)If your custom component needs to paint graphics and text then there is nothing wrong with drawing a String in the paintComponent() method. (In Swing you should override paintComponent(), not paint(). It doesn't make sense to create a JLabel with all the extra overhead that requires.
    The problem with this posting is overriding the paint(..) method of the entire frame is not a good idea.

  • Problem about calling paint method

    I have created a class to ask user input 3 floating-point numbers, using JApplet. the code list below
    import java.awt.Graphics;
    import javax.swing.*;
    public class Numbers
    double average,sum,product;
    String result;
    public void init()
    String firstNumber,secondNumber,thirdNumber;
    double num1,num2,num3;
    firstNumber=JOptionPane.showInputDialog("enter first number");
    secondNumber=JOptionPane.showInputDialog("Enter second number");
    thirdNumber=JOptionPane.showInputDialog("Enter thrid number");
    num1=Double.parseDouble(firstNumber);
    num2=Double.parseDouble(secondNumber);
    num3=Double.parseDouble(thirdNumber);
    sum=num1+num2+num3;
    product=num1*num2*num3;
    average=(num1+num2+num3)/3;
    result="";
    if(num1<num2 && num2<num3)
    result=result+num3+" is the largest number";
    if(num2>num1 && num2>num3)
    result=result+num2 +" is the largest number";
    if(num1>num2 && num2>num3)
    result=result+ num1+" is the largest number";
    public void paint(Graphics g)
    super.paint(g);
    g.drawString("sum is"+sum,25,25);
    g.drawString("product is"+ product,25,40);
    g.drawString("average is"+ average,25,60);
    g.drawString(" the largest number is"+result,25,80);
    however, after I compiled, it gave me the error message as:
    java:40: cannot resolve symbol
    symbol : method paint (java.awt.Graphics)
    location: class java.lang.Object
    super.paint(g);
    ^(pointer should point to the dot)
    don't know why,
    Message was edited by:
    ritchie_lin

    your class doesn't extend japplet or any other object for that matter. It does extend Object as all classes do, and Object has no paint method.
    Consider changing:
      public class Numbersto
      public class Numbers extends JAppletAlso, please use code tags next time you're posting code.
    Addendum: If this is not the JApplet portion of your code, it still has to subclass a Swing component that can accept painting such as JPanel. Also, with Swing you use paintComponent rather than paint.
    Message was edited by:
    petes1234

  • Does repaint() not call paint()?

    I try to create a application where pictures are switching randomly one after another. User can specific how long this randomly displaying image application run. Then when the user click "start", the image will randomly change until it is timeout. As far as I know, I have this part finish.
    However, I want to add another part: when user click start a small clock display on the panel the amount of second counting down. However, when I set the timer to repaint() the application, it does not get in the paint() method. Below are my code, please help. Since my code are a bit long, I will post my entire code on a separate thread, hope that the admin and mod dont mind.
    This is where I implement paint(), and I click on the button, I repaint the panel
    public void paint(Graphics g)
            System.out.println("Inside Graphics");
            //Create an instance of Graphics2D
            Graphics2D g2D = (Graphics2D)g;
            g2D.setPaint(Color.RED);
            g2D.setStroke(stroke);
            DigitalNumber number = new DigitalNumber(numberX,numberY,numberSize,numberGap,Color.red, Color.white);
            //Get the time that the user input to the field
            String time = tf.getText();
            float locX = numberX;
            float locY = numberY;
            //Start drawing the number onto the panel
            for(int i=0; i<time.length(); i++){
                 number.drawNumber(Integer.parseInt(Character.toString(time.charAt(i))), g2D);
                 locX += numberSize + numberGap;
                 number.setLocation(locX, locY);
    private void createBtnPanel() {
          JButton startBtn = new JButton("Start");
          JButton stopBtn = new JButton("Stop");
          startBtn.addActionListener(new StartBtnListener() );
          stopBtn.addActionListener(new StopBtnListener());
          btnPanel.add(startBtn, BUTTON_PANEL);
          btnPanel.add(stopBtn, BUTTON_PANEL);
    private class StartBtnListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             //get the time from the user input
             String input = tf.getText();
             numberOfMilliSeconds = Integer.parseInt(input)*1000;
             //get the current time
             startTime = System.currentTimeMillis();
             java.util.Timer clockTimer = new java.util.Timer();
             java.util.TimerTask task = new java.util.TimerTask()
                 public void run()
                      mainPanel.repaint();
             clockTimer.schedule(task, 0L, 1000L);
             rotatePictureTimer.start();
       }

    I am sorry. However, even though I try to make my code self contained, it still too long to post here. It is the DigitalNumber.java that contain all the strokes for draw the number is all too long. But I can tell you that DigitalNumber.java is worked because I wrote a digital clock before, and it worked. But below is the link to my DigitalNumber.java if u guy want to look at it
    http://www.vanloi-ii.com/code/code.rar
    Here is my code for DisplayImage.java in self-contain format. Thank you
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.*;
    public class DisplayImage{
       private static final Dimension MAIN_SIZE = new Dimension(250,250);
       private static final String BUTTON_PANEL = "Button Panel";
       private JPanel mainPanel = new JPanel();
       private JPanel btnPanel = new JPanel();
       private JPanel tfPanel = new JPanel();
       private BorderLayout borderlayout = new BorderLayout();
       private JTextField tf;
       BasicStroke stroke = new BasicStroke(5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
       private float numberX = 100f;
       private float numberY = 100f;
       private float numberSize = 10f;
       private float numberGap = 2f;
       public DisplayImage() {
          mainPanel.setLayout(borderlayout);
          mainPanel.setPreferredSize(MAIN_SIZE);
          createTFPanel();
          createBtnPanel();
          mainPanel.add(tfPanel, BorderLayout.NORTH);
          mainPanel.add(btnPanel, BorderLayout.SOUTH);
       public void paint(Graphics g)
            System.out.println("Inside Graphics");
            //Create an instance of Graphics2D
            Graphics2D g2D = (Graphics2D)g;
            g2D.setPaint(Color.RED);
            g2D.setStroke(stroke);
            DigitalNumber number = new DigitalNumber(numberX,numberY,numberSize,numberGap,Color.red, Color.white);
            //Get the time that the user input to the field
            String time = tf.getText();
            float locX = numberX;
            float locY = numberY;
            //Start drawing the number onto the panel
            for(int i=0; i<time.length(); i++){
                 number.drawNumber(Integer.parseInt(Character.toString(time.charAt(i))), g2D);
                 locX += numberSize + numberGap;
                 number.setLocation(locX, locY);
       private void createBtnPanel() {
          JButton startBtn = new JButton("Start");     
          startBtn.addActionListener(new StartBtnListener() );    
          btnPanel.add(startBtn, BUTTON_PANEL);
       private void createTFPanel() {
          JLabel l = new JLabel("Enter Number of Seconds: ");
          tf = new JTextField(3);
          tfPanel.add(l);
          tfPanel.add(tf);
       private class StartBtnListener implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             //get the time from the user input
             java.util.Timer clockTimer = new java.util.Timer();
             java.util.TimerTask task = new java.util.TimerTask()
                 public void run()
                      System.out.println("TimerTask");
                      mainPanel.repaint();
             clockTimer.schedule(task, 0L, 1000L);     
       private static void createAndShowUI() {
           DisplayImage displayImage = new DisplayImage();
          JFrame frame = new JFrame("Display Image");
          frame.getContentPane().add(displayImage.mainPanel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setBackground(Color.white);
          frame.pack();
          frame.setLocationRelativeTo(null);  //center the windows
          frame.setVisible(true);
       public static void main (String args[]) {
          java.awt.EventQueue.invokeLater(new Runnable(){
             public void run() {
                createAndShowUI();
    }Edited by: KingdomHeart on Feb 22, 2009 6:12 PM

  • Repaint() doesnt call paint component

    Hi all
    i need to call a paintComponent method() so i use repaint();
    but it doesnt work.
    trigger's in mouse pressed, calls pageflip method, then in a pageflip method calls paintComponent
    here's part of my code
    addMouseListener(new MouseAdapter() {                                   
                    public void mousePressed(MouseEvent e) {                   
                        if (boEvent==true){
                            System.out.println("mouse Pressed");
                            iMoux=e.getX();iMouy=e.getY();
                            if (iMoux>=(di.width/2)){
                                 boSaveReverse = false;
                                 PageFlip(0, 0, e.getX(), e.getY(), false, false, false, true);
                            else {
                                boSaveReverse = true;
                                PageFlip(0, 0, e.getX(), e.getY(), false, true, false, true);
                            boClicked=false;                                                   
    public void PageFlip(int a, int b, int c, int d, boolean boe,
                                 boolean bof, boolean bog, boolean boh){                      
                int bookx = a;int booky = b;int iMoux =c;int iMouy = d;
                boolean boClicked = boe;boolean boReverse = bof;
                boolean boZoom    = bog;boolean boDraw = boh;
                repaint();    //here repaint didint call paintComponent?       
            }did i do something wrong here?
    Thx in advance

    did i do something wrong here?Who knows? To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    luck, db

  • 3 graphic errors- Cannot resolve Symbols

    I am looking for help to resolve 3 errors that I don't understand and I am hoping someone can take the time to point me in the right directions.
    The errors occur while setting the forground color, trying to repaint and trying to draw a rectangle.
    Here are the errors from the compiler:
    Worm.java [42:1] cannot resolve symbol
    symbol : method setForeground (java.awt.Color)
    location: class Worm
    setForeground(Color.RED);
    ^
    Worm.java [49:1] cannot resolve symbol
    symbol : method repaint ()
    location: class Worm
    repaint();
    ^
    Worm.java [56:1] cannot resolve symbol
    symbol : method drawRectangle (int,java.awt.Rectangle,int,int)
    location: class java.awt.Graphics
    g.drawRectangle(rec.x, rec[i], rec[i].height, rec[i].width );
    ^
    3 errors
    Errors compiling Worm.java.
    The code follows:
    Thanks for any assistance inadvance
    WBR
    import java.awt.*;
    import java.awt.Graphics.*;
    import java.awt.Color;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.Rectangle.*;
    import java.io.*;
    import java.util.*;
    class WormFrame extends JFrame{   
        public WormFrame(){
            setTitle("CenteredFrame");
            addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e){
                    System.exit(0);
            Toolkit tk = Toolkit.getDefaultToolkit();
            Dimension d = tk.getScreenSize();
            int screenHeight = d.height;
            int screenWidth = d.width;
            setSize(screenWidth / 2, screenHeight / 2);
            setLocation(screenWidth / 4, screenHeight / 4);
    public class Worm{
        Rectangle rec[];
        private Worm(){
            Rectangle rec[] = new Rectangle [25];
            int x = 25;
            int y = 25;
            for(int i = 0; i < rec.length; i++ ){
                rec.x = x++;
    rec[i].y = y++;
    rec[i].height = 1;
    rec[i].width = 1;
    private void wormDraw( ){
    setForeground(Color.RED); // Error 1
    for(int a = 1; a < 20; a++){
    for(int i = 1; i < rec.length; i++ ){
    rec[i].x += 1;
    rec[i].y += 1;
    repaint(); // Error 2
    public void paint(Graphics g) {
    System.out.println("paint : " + new Date( ) );
    // Draw dots
    for(int i = 0; i < rec.length; i++ ){
    g.drawRectangle(rec[i].x, rec[i], rec[i].height, rec[i].width ); // Error 3
    public static void main(String[] args){
    JFrame frame = new WormFrame();
    frame.show();
    Worm w = new Worm();
    w.wormDraw();

    Hello! This works...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class Worm extends JFrame
         Rectangle rec[];   
         public Worm()
               setTitle("CenteredFrame");       
            addWindowListener(new WindowAdapter(){
                 public void windowClosing(WindowEvent e){               
                     System.exit(0);           
            Toolkit tk = Toolkit.getDefaultToolkit();       
            Dimension d = tk.getScreenSize();       
            int screenHeight = d.height;       
            int screenWidth = d.width;       
            setSize(screenWidth / 2, screenHeight / 2);       
            setLocation(screenWidth / 4, screenHeight / 4);  
            setVisible(true);
              rec = new Rectangle [25];       
              int x = 25;       
              int y = 25;       
              for(int i = 0; i < rec.length; i++ )
                   System.out.println("Creating rec " + i);        
                   rec[i] = new Rectangle();
                   rec.x = x++;
                   rec[i].y = y++;
                   rec[i].height = 1;
                   rec[i].width = 1;
         public void wormDraw( )
              setForeground(Color.RED);
              for(int a = 1; a < 20; a++)
                   for(int i = 1; i < rec.length; i++ )
                        System.out.println("Drawing rec " + i);
                        rec[i].x += 1;
                        rec[i].y += 1;
              System.out.println("Calling paint");
              repaint();
              validate();
              System.out.println("Done");
         public void paint(Graphics g)
              System.out.println("paint : " + new Date( ) );
              for(int i = 0; i < rec.length; i++ )
                   g.fillRect(rec[i].x, rec[i].y, rec[i].height, rec[i].width);
         public static void main(String[] args)
              new Worm().wormDraw();           
    regards,
    Liam

  • Why dont we call method paint?? and declare it instead

    usually i have seen from previous examplies in my bok that we declare methods somewhere and then we call them sending arguments but in case of paint i saw only declaration as follows
    public void paint(Graphics g){
    after declaring why is there no code like this:paint(g1);
    why no call and still paint does the work .its confusing

    Two answers to that:
    1) JVM calls paint on its own whenever it detects a need to redraw the screen. This can occur when something is added to it, when a frame is partially covered, moved, resized, etc...
    2) paint can sometimes be called programmatically using the repaint() method. This is preferable to calling paint because it finds the correct Graphics object and makes sure that everything that needs a repaint gets its paint method called...
    Steve

  • Updating frame content between Thread.sleep() calls

    I have several JLabels in a Frame. What I want is to update the content of the labels (to be more precise, the ImageIcons), but with pauses in between each update (lets say 1 second). So, I want to change the content of one label, have those changes show on screen, then, wait for a second and change the content of the second label, show the changes, wait for a second, change the next label, and so on...
    What I'm doing is:
    change label 1
    Thread.sleep(1000);
    change label 2
    Thread.sleep(1000);
    change label 3
    Thread.sleep(1000);
    ...And the problem is that the individual changes are not shown on screen until the whole process has finished. It does pause after each change, but the change to the particular label is not shown afterwards. Then, when the whole process is finished, the changes to all the labels are shown simultaneously on screen.
    I have tried calling repaint() and validate() after each call to Thread.sleep(), but it makes no difference.
    Why are the changes not updated on screen until the end?
    How can I achieve what I'm trying to do?
    Many thanks in advance.

    You're sleeping in the main thread, so you're holding up the paint thread too...
    I'd trying extending each label / visual component, to include it's own timer and thread.
    eg. ( not compiled nor tested, but addresses all the main points... )
    regards,
    Owen
    public class myLabel extends JLabel implements runnable
        boolean animate = true;
        Thread paintThread;
         public myLabel ( )
              super();
              paintThread = new Thread ( this );
         public void startAnimation ( )
              if ( animate == false )
                 animate = true;
                 paintThread.start();
         pubic void stopAnimation ( )
             animate = false;
         public void run ( )
               while ( !animate )
                   Thread.sleep ( 1000 );
                    final Runnable runnable = new Runnable()
                        public void run()
                              // change label text
                              // Make any Swing / GUI changes here                      
                        } // run
                   };    // runnable
                   // force/flag this label as requiring a repaint
                   invalidate();              
                   // NB : You must use this to avoid multi-threaded problems with Swing
                   SwingUtilities.invokeLater(runnable);
    }

  • Paint Component

    Hi all
    i have four classes plot , plot3d, plotsurface and test
    plot is derived from JPanel and plot3d and plotsurface extend plot class
    i am trying to do a very simple operation . just making a tool bar with 2 buttons to switch between plots .
    the 2 plot classes plot3d and plotsurface just draw a line on the screen
    problem is that when the user clicks one button it doesnot show up on the screen but when the window is resized it does call paint component of the corresponding class
    can Any one explain why this is happening......
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public abstract class plot extends JPanel {
    plot()
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plot3d extends plot {
    plot3d(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(200,200,320,320);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plotsurface extends plot {
    plotsurface(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(120,120,140,140);
    package test;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics2D.*;
    import java.applet.*;
    public class Test extends javax.swing.JApplet {
    private Container container;
    public Rectangle rect;
    JPanel toolBar;
    JButton contourButton;
    JButton surfaceButton;
    JPanel toolPanel;
    public Graphics g;
    public test.plot3d graph3D;
    public test.plotsurface graphSurface;
    private int plotType=0;
    private void graph3D(Graphics2D g2)
    graph3D=new plot3d(false);
    public void graphSurface(Graphics2D g2)
              graphSurface=new plotsurface(false);
    private void changeplottoContour()
    if(plotType==0)
    return;
    plotType=0;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graphSurface=null;
    System.gc();
    graph3D(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graph3D,BorderLayout.CENTER);
    private void changeplottoSurface()
    if(plotType==1)
    return;
    plotType=1;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graph3D=null;
    System.gc();
    graphSurface(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graphSurface,BorderLayout.CENTER);
    private void surfaceButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoSurface();
         repaint();
    private void contourButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoContour();
         repaint();
    public void init()
         container=getContentPane();
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    Rectangle r1= new Rectangle();
    rect=new Rectangle();
    //r1=container.getBounds();
    toolPanel= new JPanel(new BorderLayout());
    toolBar = new JPanel();
    contourButton = new JButton("Contour");
    toolBar.add(contourButton);
    contourButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    contourButtonActionPerformed(evt);
    surfaceButton = new JButton("Surface Plot");
    toolBar.add(surfaceButton);
    surfaceButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    surfaceButtonActionPerformed(evt);
    toolBar.setBackground(Color.white);
    toolPanel.add(toolBar,BorderLayout.NORTH);
    container.add(toolPanel,BorderLayout.NORTH);
    Rectangle r2= toolPanel.getBounds();
    Dimension appletSize = this.getSize();
    int appletHeight= appletSize.height;
    int appletWidth= appletSize.width;
              rect.setBounds(0,(int)r2.getHeight(),appletWidth,appletHeight-(int)r2.getHeight());
    plotType=0;
         graph3D(g2);
         container.add(graph3D,BorderLayout.CENTER);

    in your button action listeneres (e.g. contourButtonActionPerformed()) don't only call repaint(), but update(this.getGraphics());
    this should help in most cases. other refreshing methods are:
    java -Dsun.java2d.noddraw=true HelloWorld
    java.awt.Component.repaint()
    java.awt.Component.update(Graphics) (e.g. c.update(c.getGraphics());)
    java.awt.Component.validate()
    javax.swing.JComponent.revalidate()
    javax.swing.JComponent.updateUI()
    javax.swing.SwingUtilities.updateComponentTreeUI(java.awt.Component)

  • Difference between manual resize and repaint, invalidate, validate etc etc?

    Using Jdk 1.5 and under windows XP I am drawing directly in a JPanel.
    And thus creating a drawing of my own when the system calls:
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    Line2D lineInArrow =
    new Line2D.Double(. . . );
    g2.draw(lineInArrow);
    Ellipse2D ellipse = new Ellipse2D.Double(. . . );
    g2.draw(ellipse);
    The program of course has much more detail but that is the essence of it.
    Now, it turns out that my drawings sometimes become rather messed up and needs to be redrawn so I have tried calling. repaint(), invalidate(), validate(), paintImmediately() in many different combinations and several times.
    As the system is a more complex than just a JPanel - the JPanel is
    contained in a JScrollPane for instance and all is set in a JDialog - I have also tried calling the different parts with these methods and in many different combinations.
    Even calling the parts repeatedly from another Thread so that the methods get called every second or so does not help.
    NOTHING HAPPENS to the messed up drawing
    UNLES I DO A MANUAL RESIZE of the window. Then the drawing becomes OK!!!
    Yes, you guessed right, I have also tried resizing from the program
    by calls such as:
    Dimension currentSize = this.getSize();
    this.setSize(100, 100);
    this.setSize(currentSize);
    repaint();
    The window flickers - gets smaller and then gets back to its original size.
    But the drawing, if messed up, is still messed up in exactly the same way.
    SO WHAT IS HAPPENING WHEN I DO A MANUAL RESIZE BUT NEVER HAPPENS WHEN I DO ANY OF THE ABOVE?
    And, can I somehow initiate this - whatever it is - by programming rather than by a manual resizing of the window??

    With messed up I simply mean that it is not properly redrawn.
    For example a rectangle that should have been drawn is not shown - not drawn. Or a String is not drawn in its proper place.
    But when I do a manual resize (using the mouse) things are drawn correctly. Sometimes I have to do more than one resize to get everything drawn correctly.
    I might also add that I have tried some other more or less weird strategis to get this "manual resize like painting" activated such as:
    Calling the paintComponent method directly:
    Graphics g = this.mainDrawPanel.getGraphics();
    mainDrawPanel.paintComponent(g);
    Trying to make the system understand that something DO have changed:
    JButton aDummyButton = new JButton("Hi there - did you see me??");
    mainDrawPanel.add(aDummyButton);
    this.repaint();
    mainDrawPanel.remove(aDummyButton);
    this.repaint();
    Nothing makes anything happen - except the manual resize of the window.
    So what is so special about a manual resize of a window? What actually goes on when this happens? - That does NOT happen in all the other attempts?

  • Component.validate() leaves invalidated

    Hello,
    I have the following problem:
    nodeComp.validate();
    if (!nodeComp.isValid())
         System.err.println("Component is invalid!!!");It keeps printing that the component is invalid.
    I am using a JComponent as a stamp (same as in JTable) so my component is not really added to any container.
    PS: bsampieri are you there?

    yeah...
    Did you read the API docs on what validate() and isValid() means? I don't believe, from reading them just now, that they are that closely related.
    validate() -- Ensures that this component has a valid layout. This method is primarily intended to operate on instances of Container.
    isValid() -- Determines whether this component is valid. A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid.
    What's the real problem? That it says it's valid or not shouldn't matter. If you call setSize() and validate(), after that you should be able to call paint() on the component with another graphics object to draw that component on the graphics.

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

Maybe you are looking for

  • USB ports and Pocket Drive Unrecognized (IQ-775)

    Hi all: With no warning, the two front USB ports stopped  functioning (rear ones are OK) and the Pocket Drive is no longer recognized. Worked one day, did not work the next. This happened simultaneously, so I assume it is related as the Pocket Drive

  • Can I update directly from iPhoto 8.1.2 to 9.3.2 without problems?

    I'm not sure whether to  update  from my iPhoto 8.1.2 straight to the update of iPhoto 9.3.2 or should I go update to update? The updates I found after my 8.1.2 are 9.1,  9.1.1 9.1.3 9.1.5 9.2.1 9.2.2 9.2.3 9.3 9.3.1 9.3.2

  • How to collapse unused text field in PDF form

    Hi all, may i know how to collapse unused text field in a PDF form. Etc, we have alot of description line for user to enter the info, but some line will be left unused, so i was wondering whether can i hide those unused text field. But when i need th

  • Reflection

    Hi , I am developing a code. 1. we pass an object to a method (reflectObject) 2. reflectObject return a new object which is a true copy . I am using the reflection but in one condition when a class contain any object of other class that time i am una

  • Function to generate a random ID

    Hello all, Do we have any inbuilt function in SAP to generate a random alphanumeric ID? The requirement is such that there is an import parameter "Sales Rep ID" which is optional. So if the user is not providing the ID, then we have to randomly gener