Results 1 to 14 of 14
  1. #1
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default plz help me solving this small but annoying problem!! plz.. i need help urgently.

    public void paintComponent(final Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);

    jButton1.addActionListener(
    new ActionListener() {

    public void actionPerformed(ActionEvent event) {
    if (event.getSource() == jButton1) {
    g.drawLine(100,100,100,100);
    }
    }
    });
    }



    I made a panel and added to it a button. What I want exactly is that when I press this button a line should be drawn..


    The problem is the object 'g' isn't responding i.e., I am unable to use it to plot the line. Plz help:(

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,354
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Y. Progammer View Post
    public void paintComponent(final Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);

    jButton1.addActionListener(
    new ActionListener() {

    public void actionPerformed(ActionEvent event) {
    if (event.getSource() == jButton1) {
    g.drawLine(100,100,100,100);
    }
    }
    });
    }



    I made a panel and added to it a button. What I want exactly is that when I press this button a line should be drawn..


    The problem is the object 'g' isn't responding i.e., I am unable to use it to plot the line. Plz help:(
    Don't add that action listener to the button in the paintComponent( ... ) method; that method is called many many times so you end up with as many action listeners all connected to that single button.

    An alternative scenario would be something like this: first define an interface for something that can draw:

    Java Code:
    public interface Drawer {
       void draw(Graphics g);
    }
    Next, define a List<Drawer> drawerList in your components and methods to add and remove Drawers to/from it. Finally add the following code to your paintComponent( ... ) method:

    Java Code:
    for (Drawer d : drawerList)
       d.draw(g);
    in words: when the component needs painting offer all registered Drawers an opportunity to draw on the Graphics.

    Your line drawing Drawer would look something like this:

    Java Code:
    new Drawer() {
       public void draw(Graphics g) {
          g.drawLine(100,100,200,200); // not to 100,100; read the API
       }
    }
    ... and add it to that list once. Writing that last piece of code I realized that your original drawer draws a line from point 100,100 to point 100,100; i.e. it is (almost) invisible. Nevertheless, the scenario I outlined above is better than registering listeners in the paintComponent( ... ) method over and over again.

    kind regards,

    Jos

  3. #3
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default

    Why it is that adding action listener to the button in the paintComponent( ... ) method; that method is called many many times..??? plz explain.

  4. #4
    collin389 is offline Senior Member
    Join Date
    Nov 2009
    Posts
    235
    Rep Power
    5

    Default

    paintComponent is called every time that it needs to draw the window. That is, whenever you move, or resize it. and if you make a new oject, action listener, and keep adding it to the button, your button will be calling every single action listener. Ex. you drag your window 500 pixels, about half a screen. Depending on how slow you drag it, paintComponent will be called around 500 times. That means that you have created 501 action listeners which is horrible for memory, when you click the button, it will draw the line, and then call paintComponent() to redraw it. that means that for every action listener, drawLine() and therefore paintComponent() will be called, resulting in more action listeners, 1002. this is obviously even worse for memory. and a horrible way to try to paint something.

  5. #5
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,354
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Y. Progammer View Post
    Why it is that adding action listener to the button in the paintComponent( ... ) method; that method is called many many times..??? plz explain.
    Put the following line in your paintComponent( ... ) method and see for yourself:

    Java Code:
    System.out.println("adding another listener ...");
    kind regards,

    Jos

  6. #6
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default

    Java Code:
    jButton.addActionListener(
                    new ActionListener() {
    
                        public void actionPerformed(ActionEvent event) {
                            if (event.getSource() == jButton) {
                                System.out.println("sd");
                            }
                        }
                    });
    Thnx for reply but I do have few more questions !

    PROBLEM 1:
    My questions are based on following two observations::

    OBSERVATION 1:

    run the file..
    press button
    [output]
    sd
    sd
    minimized window
    maximized window
    press button
    [output]
    sd
    sd
    sd
    minimized window
    maximized window
    press button
    [output]
    sd
    sd
    sd
    sd
    minimized window
    maximized window
    press button
    [output]
    sd
    sd
    sd
    sd
    sd

    In this observation it is clear that whenever the window appears again and again.. the paintComponent() method is called and consequently yet another actionListener is added to the button apart existing actionListeners and when the button is pressed all the current actionListeners respond. ok. thats fine.

    [COLOR="rgb(46, 139, 87)"]OBSERVATION 2[/COLOR]:

    run the file..
    press button
    [output]
    sd
    sd
    press button
    [output]
    sd
    sd
    press button
    [output]
    sd
    sd
    press button
    [output]
    sd
    sd

    In this observation the window appears only once that is it never minimized and maximized nor it is ever resized and so the paintComponent() method is never called again and again and so the number of initially existing actionListeners respond. ok. thats f9.

    But the big questions is that ... why the "number of actionListeners = 2 " for the very first time when the file is run.. (as observable from the output above sd sd).
    plz explain.. how many times the method paintComponent() method is called initailly and from where and why it is called twice making the number of actionListeners = 2.

    PROBLEM 2:

    Java Code:
    jButton.addActionListener(
                    new ActionListener() {
    
                        public void actionPerformed(ActionEvent event) {
                            if (event.getSource() == jButton) {
                                g.drawLine(100,100,600,600);
                            }
                        }
                    });
    ok. I understood that this method of adding actionListner from inside that paintComponent() method is wrong way to draw anything.. but my question is why it is that the line is never drawn when the button is pressed.{It is never drawn.. I checked myself.} Why it happened.. plz explain.:confused:

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    In all likelihood the Graphics object you are drawing with is no longer the current active graphics object. The bottom line is that this approach is completely wrong.

    I don't know why paintComponent is called initially twice, but I do know that we have only limited control as to when and how often it gets called. We can suggest that it be called via repaint(), but even this is sometimes ignored.

    Also, regarding your "urgency", please understand that this can sometimes have the opposite effect that you intend, that sometimes stating this in a thread title will induce others not to reply. To learn why, please have a look at this link from JavaRanch: Ease Up

    Much luck!
    Last edited by Fubarable; 02-20-2010 at 05:59 PM.

  8. #8
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default

    ok. I would keep in mind for the new threads.. and thanx for the reply.

    But what about PROBLEM 2:

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Y. Progammer View Post
    ok. I would keep in mind for the new threads.. and thanx for the reply.
    cool.

    But what about PROBLEM 2:
    I answered that in the first statement of my reply above.

  10. #10
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default

    sO which object is the currently active object??

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Y. Progammer View Post
    sO which object is the currently active object??
    The currently active Graphics object is the one that is passed to the paintComponent method at the time that this method is called. Please read all you can at the Sun/Oracle tutorials on Swing graphics as it will explain all and will really help you immensely. Honest.

  12. #12
    Y. Progammer is offline Member
    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0

    Default

    can you plz give the exact link.. thanx.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Some example code that shows lines being drawn on the press of a button that might or might not help you:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Line2D;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    import javax.swing.*;
    
    public class DrawLineEg extends JPanel {
      private boolean showRedLine = false;
      private Random random = new Random();
      private List<Line2D> randomLineList = new ArrayList<Line2D>();
    
      public DrawLineEg() {
        setPreferredSize(new Dimension(700, 500));
     
        // button to show or hide red line.  The button simply toggles
        // the value of a boolean variable, showRedLine, calls repaint 
        // on the main JPanel and the paintComponent method decides whether or
        // not to draw the line depending on the value of showRedLine
        JButton toggleLineBtn = new JButton("Toggle Red Line");
        toggleLineBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            showRedLine = !showRedLine;
            DrawLineEg.this.repaint();
          }
        });
        
        // this button will create a random Line2D object and add it to a 
        // List<Line2D> called randomLineList and then calls repaint()
        // the paintComponent method will iterate through this list, painting
        // all Line2D objects in the list.  Because this requires a Graphics2D object, 
        // the paintComponent's Graphics object must be explicitely cast to a 
        // Graphics2D object before this will work
        JButton addRandomLineBtn = new JButton("Add Random Blue Lines");
        addRandomLineBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Dimension size = DrawLineEg.this.getSize();
            
            int x1 = random.nextInt(size.width);
            int y1 = random.nextInt(size.height);
            int x2 = random.nextInt(size.width);
            int y2 = random.nextInt(size.height);
            
            Line2D line = new Line2D.Double(x1, y1, x2, y2);
            randomLineList.add(line);
            DrawLineEg.this.repaint();
          }
        });
        
        add(toggleLineBtn);
        add(addRandomLineBtn);
      }
      
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        // draw red line if boolean true
        if (showRedLine) {
          g.setColor(Color.red);
          g.drawLine(100, 100, 600, 300);
        }
        
        g.setColor(Color.blue);
        // draw all random lines held in randomLineList
        Graphics2D g2 = (Graphics2D) g;
        for (Line2D line : randomLineList) {
          g2.draw(line);
        }
      }
      
      private static void createAndShowUI() {
        JFrame frame = new JFrame("DrawLineEg");
        frame.getContentPane().add(new DrawLineEg());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }

Similar Threads

  1. small problem
    By barusk in forum Networking
    Replies: 4
    Last Post: 03-21-2009, 06:19 AM
  2. Solving this equations problem in Java
    By matt_well in forum New To Java
    Replies: 17
    Last Post: 08-30-2008, 09:05 PM
  3. Suggestions required for solving a Java problem
    By bilal_ali_java in forum Advanced Java
    Replies: 3
    Last Post: 08-16-2008, 01:11 AM
  4. Small problem
    By ayoood in forum New To Java
    Replies: 2
    Last Post: 06-06-2008, 12:27 PM
  5. Annoying database problem!
    By DC1 in forum New To Java
    Replies: 2
    Last Post: 05-29-2008, 09:43 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •