Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.gui > #4961 > unrolled thread

How do I paint on an existing Panel?

Started by"A B" <@bleBaker.uk>
First post2012-01-18 16:55 +0000
Last post2012-02-17 17:08 -0800
Articles 13 on this page of 33 — 10 participants

Back to article view | Back to comp.lang.java.gui


Contents

  How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-01-18 16:55 +0000
    Re: How do I paint on an existing Panel? Knute Johnson <nospam@knutejohnson.com> - 2012-01-18 09:29 -0800
      Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-01-18 18:12 +0000
        Re: How do I paint on an existing Panel? Knute Johnson <nospam@knutejohnson.com> - 2012-01-18 15:00 -0800
    Re: How do I paint on an existing Panel? markspace <-@.> - 2012-01-18 10:55 -0800
    Re: How do I paint on an existing Panel? Roedy Green <see_website@mindprod.com.invalid> - 2012-01-20 19:54 -0800
    Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-01-30 17:59 +0000
    Re: How do I paint on an existing Panel? Neil Morris <neil.morris4@googlemail.com> - 2012-02-04 20:58 +0000
      Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-02-05 01:01 -0800
      Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-10 12:10 +0000
      Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-16 20:55 +0000
        Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-02-16 13:04 -0800
          Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-16 21:33 +0000
    Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-16 21:05 +0000
      Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-02-16 13:28 -0800
        Re: How do I paint on an existing Panel? "John B. Matthews" <nospam@nospam.invalid> - 2012-02-16 21:18 -0500
        Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-17 18:20 +0000
          Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-02-17 10:45 -0800
          Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-02-17 10:49 -0800
            Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-19 19:31 +0000
              Re: How do I paint on an existing Panel? Lew <noone@lewscanon.com> - 2012-02-19 14:41 -0800
                Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-03-04 16:51 +0000
                  Re: How do I paint on an existing Panel? Jeff Higgins <jeff@invalid.invalid> - 2012-03-04 12:36 -0500
                  Re: How do I paint on an existing Panel? Lew <noone@lewscanon.com> - 2012-03-04 10:47 -0800
                  Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-03-14 17:39 +0000
                    Re: How do I paint on an existing Panel? Lew <lewbloch@gmail.com> - 2012-03-14 11:07 -0700
                    Re: How do I paint on an existing Panel? "John B. Matthews" <nospam@nospam.invalid> - 2012-03-14 23:01 -0400
                    Re: How do I paint on an existing Panel? markspace <-@.> - 2012-03-15 09:30 -0700
          Re: How do I paint on an existing Panel? Knute Johnson <nospam@knutejohnson.com> - 2012-02-17 17:01 -0800
      Re: How do I paint on an existing Panel? Knute Johnson <nospam@rabbitbrush.frazmtn.com> - 2012-02-16 13:59 -0800
        Re: How do I paint on an existing Panel? "A B" <@bleBaker.uk> - 2012-02-17 18:07 +0000
          Re: How do I paint on an existing Panel? Knute Johnson <nospam@knutejohnson.com> - 2012-02-17 17:04 -0800
          Re: How do I paint on an existing Panel? Knute Johnson <nospam@knutejohnson.com> - 2012-02-17 17:08 -0800

Page 2 of 2 — ← Prev page 1 [2]


#5046

FromLew <noone@lewscanon.com>
Date2012-02-19 14:41 -0800
Message-ID<jhrtr0$ik5$1@news.albasani.net>
In reply to#5045
On 02/19/2012 11:31 AM, A B wrote:
> "Lew" <lewbloch@gmail.com> wrote in message
> news:10534455.131.1329504571649.JavaMail.geo-discussion-forums@pbgq3...
>> "A B" wrote:
>>> Lew wrote:
>>> > I'm less familiar with idioms that interfere with the repainting loops,
>>> > but
>>> > shouldn't you be invalidating? Do you actually have to repaint?
>>>
>>> Shouldn't I be which?
>>
>> Invalidating.
>> <http://lmgtfy.com/?q=Java+Swing+invalidate>

> Bear in mind that I couldn't possibly have searched for that because I had no
> idea "invalidating" was anything to do with Swing, since I don't know what it
> is. Or are you just putting it like that to save finding it yourself?

Silly question. I always follow the links myself that I post, to make sure 
that they're useful.

Of *course* you could have searched for it yourself. That was my point.

How did you know it had anything to do with Swing? Because it was presented as 
something you need to do in Swing, duh. It couldn't be more obvious.

So, this is a Java newsgroup, in a thread about Swing, where you are curious 
about the meaning of "invalidate".

So it is blazingly obvious that your first, simplest, least-effort movement of 
your arse would be to search on the phrase "Java Swing invalidate".

To be a successful programmer, you must be willing to invest the barest 
minimum of thought into your actions.

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#5071

From"A B" <@bleBaker.uk>
Date2012-03-04 16:51 +0000
Message-ID<4f539d9d$0$2958$fa0fcedb@news.zen.co.uk>
In reply to#5046
"Lew" <noone@lewscanon.com> wrote on 19th February:
> On 02/19/2012 11:31 AM, A B wrote:
>> "Lew" <lewbloch@gmail.com> wrote in message
>> news:10534455.131.1329504571649.JavaMail.geo-discussion-forums@pbgq3...
>>> "A B" wrote:
>>>> Lew wrote:
>>>> > I'm less familiar with idioms that interfere with the repainting 
>>>> > loops,
>>>> > but
>>>> > shouldn't you be invalidating? Do you actually have to repaint?
>>>>
>>>> Shouldn't I be which?
>>>
>>> Invalidating.
>>> <http://lmgtfy.com/?q=Java+Swing+invalidate>
>
>> Bear in mind that I couldn't possibly have searched for that because I 
>> had no
>> idea "invalidating" was anything to do with Swing, since I don't know 
>> what it
>> is. Or are you just putting it like that to save finding it yourself?
>
> Silly question. I always follow the links myself that I post, to make sure 
> that they're useful.
>
> Of *course* you could have searched for it yourself. That was my point.
>
> How did you know it had anything to do with Swing? Because it was 
> presented as something you need to do in Swing, duh. It couldn't be more 
> obvious.
>
> So, this is a Java newsgroup, in a thread about Swing, where you are 
> curious about the meaning of "invalidate".
>
> So it is blazingly obvious that your first, simplest, least-effort 
> movement of your arse would be to search on the phrase "Java Swing 
> invalidate".

I repeat.  For all I knew, "invalidating" was some arcane property of Java 
itself, applying to Swing and every other stinking class in the stinking 
language.  The word doesn't exactly scream GUI, does it?  (GUI would be a 
hard word to scream, mind you ;-))
Any case, nobody thinks of everything, and having finally got your link past 
my Javascript filter I see you were being even more unnecessarily rude about 
it than I thought.  (And most of the results assume knowledge of things I 
haven't done yet.  That's the other reason I don't start with a web search - 
they're random.)

> To be a successful programmer, you must be willing to invest the barest 
> minimum of thought into your actions.

Yes, I had a bad day, too.  (That's why I didn't open your posting before. 
I wasn't in the mood to upset myself with what you were likely to have put, 
by previous record.)  Right, I'm off, so you have your wish.

-- 
A. B.
><>
My e-mail address is zen177395 at  zendotcodotuk, though I don't check that 
account very often.
Post unto others as you would have them post unto you. 

[toc] | [prev] | [next] | [standalone]


#5072

FromJeff Higgins <jeff@invalid.invalid>
Date2012-03-04 12:36 -0500
Message-ID<jj094u$iic$1@dont-email.me>
In reply to#5071
On 03/04/2012 11:51 AM, A B wrote:
> stinking language
>(GUI would be a hard word to scream, mind you ;-))
World class GUI scream, yes.
cf Fred Patzel, Pig-hoo-eey

[toc] | [prev] | [next] | [standalone]


#5073

FromLew <noone@lewscanon.com>
Date2012-03-04 10:47 -0800
Message-ID<jj0dbf$f13$1@news.albasani.net>
In reply to#5071
A B wrote:
> Lew wrote:
>> To be a successful programmer, you must be willing to invest the barest
>> minimum of thought into your actions.
>
> Yes, I had a bad day, too. (That's why I didn't open your posting before. I
> wasn't in the mood to upset myself with what you were likely to have put, by
> previous record.) Right, I'm off, so you have your wish.

Some people respond to good advice with proper action. Some get their knickers 
in a twist and ego in the way. Try following my advice instead of being all 
pissy about it.

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg

[toc] | [prev] | [next] | [standalone]


#5087

From"A B" <@bleBaker.uk>
Date2012-03-14 17:39 +0000
Message-ID<4f60d7b6$0$5256$db0fefd9@news.zen.co.uk>
In reply to#5071
I got it working.  Turned out that it just wanted paint() in place of 
paintComponent() for some reason.
Sorry I said what I did, Lew, just in a bad mood for entirely other reasons.
The proper Java book I'd ordered (Just Java 2) has now arrived, so I 
shouldn't be bothering you again.
Thanks for all the help, everyone.
-- 
A. B.
><>
My e-mail address is zen177395 at  zendotcodotuk, though I don't check that 
account very often.
Post unto others as you would have them post unto you. 

[toc] | [prev] | [next] | [standalone]


#5088

FromLew <lewbloch@gmail.com>
Date2012-03-14 11:07 -0700
Message-ID<30192746.187.1331748468722.JavaMail.geo-discussion-forums@pbbls7>
In reply to#5087
On Wednesday, March 14, 2012 10:39:03 AM UTC-7, A B wrote:
> I got it working.  Turned out that it just wanted paint() in place of 
> paintComponent() for some reason.
> Sorry I said what I did, Lew, just in a bad mood for entirely other reasons.
> The proper Java book I'd ordered (Just Java 2) has now arrived, so I 
> shouldn't be bothering you again.
> Thanks for all the help, everyone.

Happens to the best of us. Mazeltov on the new book; may it serve you well.

You will find _Effective Java_ of significant help to your general Java wisdom. (Current edition is 2nd edition - 1st edition might be available and is of help with older versions of Java like Java 2.)

-- 
Lew

[toc] | [prev] | [next] | [standalone]


#5089

From"John B. Matthews" <nospam@nospam.invalid>
Date2012-03-14 23:01 -0400
Message-ID<nospam-A1B556.23013214032012@news.aioe.org>
In reply to#5087
In article <4f60d7b6$0$5256$db0fefd9@news.zen.co.uk>,
 "A B" <@bleBaker.uk> wrote:

> I got it working.  Turned out that it just wanted paint() in place of 
> paintComponent() for some reason.

By way of explanation, your code extends JFrame, which has no 
paintComponent() method to override. Using the annotation, @Override, 
might have highlighted the problem. In contrast, Knute's example 
extends JPanel and overrides paintComponent().

In general "Swing programs should override `paintComponent()` instead 
of overriding `paint()`."—Painting in AWT and Swing: The Paint Methods. 

<http://java.sun.com/products/jfc/tsc/articles/painting/index.html#callbacks>

-- 
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

[toc] | [prev] | [next] | [standalone]


#5090

Frommarkspace <-@.>
Date2012-03-15 09:30 -0700
Message-ID<jjt5es$i56$1@dont-email.me>
In reply to#5087
On 3/14/2012 10:39 AM, A B wrote:
> I got it working. Turned out that it just wanted paint() in place of
> paintComponent() for some reason.


This sounds really wrong.  I just dug my book Swing Hacks out of 
storage, and this is the first example: how to draw an image on a 
JPanel.  They point out you have to use paintComponent() or the children 
inside the panel will not be drawn.

OTOH, maybe that's the problem.  If paint() doesn't draw the children, 
maybe one of the components inside your panel is drawing on top of your 
image.

[toc] | [prev] | [next] | [standalone]


#5039

FromKnute Johnson <nospam@knutejohnson.com>
Date2012-02-17 17:01 -0800
Message-ID<jhmt9e$1tq$1@dont-email.me>
In reply to#5034
On 2/17/2012 10:20 AM, A B wrote:
>>> Graphics2D g = (Graphics2D)g2d;
>>
>> Your naming is backwards.
>
> That's how Knute did it. I thought that was funny, too, but I didn't
> want to complicate things.

Yes, it is backwards, that was just me screwed up.

-- 

Knute Johnson

[toc] | [prev] | [next] | [standalone]


#5030

FromKnute Johnson <nospam@rabbitbrush.frazmtn.com>
Date2012-02-16 13:59 -0800
Message-ID<jhju7b$f12$1@dont-email.me>
In reply to#5026
On 2/16/2012 1:05 PM, A B wrote:
> Sorry, I'm stumped, again. I really have been trying to sort it out
> myself, but no luck. I've done it by adapting Knute Johnson's code
> (which works fine in itself). Mine now defines a line and calls
> repaint() as nice as you like, but there's no answer.
>
> I've chopped the code back to just the bits directly involved with the
> drawing and sprinkled debugging statements everywhere, which established
> that the bit that calls paintComponent() (via repaint() - that's right
> isn't it?) is firing but paintComponent() itself isn't. Here's what's
> left, if you're interested. Sorry if anyone finds it hard to read, I
> don't know how you like it formatted.
>
> ------------------------
> import java.awt.*;
> import java.awt.event.*;
> import java.awt.geom.*;
> import java.util.*;
> import javax.swing.*;
>
> public class Vectorine extends JFrame implements MouseListener
> {
> private static final long serialVersionUID = 159L;
> // List to contain all the lines generated
> private final java.util.List<ColoredLine> lineList = new
> java.util.ArrayList<ColoredLine>();
>
> public static void main() {Vectorine v = new Vectorine();}
>
> public Vectorine()
> {
> super("Vectorine");
> setSize(200, 200);
> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
> setVisible(true);
>
> // Set up window's initial contents
> Container contentArea = getContentPane();
> FlowLayout layout = new FlowLayout();
> contentArea.setLayout(layout);
> JPanel panelA = new JPanel();
> panelA.addMouseListener(this);
> contentArea.add(panelA);
> setContentPane(contentArea);
>
> System.out.println("If you click anywhere in the box, 3 random lines
> should appear in it.");
> }
>
> public void paintComponent(Graphics g2d)
> {
> Graphics2D g = (Graphics2D)g2d;
> System.out.println("Painting...");
> for (ColoredLine hand : lineList)
> {
> System.out.println("Drawing line...");
> BasicStroke pen = new BasicStroke(hand.getThickness());
> g.setStroke(pen);
> g.setColor(hand.getColor());
> g.draw(hand);
> }
> }
>
> public void mouseClicked(MouseEvent event)
> {
> System.out.println("Mouse clicked");
> double xcoord = 0, ycoord = 0;
> for (int count=0; count<3; count++)
> {
> xcoord = 100 * Math.random();
> ycoord = 100 * Math.random();
> System.out.println("xcoord="+xcoord+", ycoord="+ycoord);
> ColoredLine hand = new ColoredLine(0F, 0F, (float)xcoord, (float)ycoord,
> Color.red, 2);
> lineList.add(hand);
> System.out.println("Calling repaint()...");
> repaint();
> }
> }
>
> /** Blank methods to keep MouseListener happy. */
> public void mousePressed(MouseEvent event) {}
> public void mouseReleased(MouseEvent event) {}
> public void mouseEntered(MouseEvent event) {}
> public void mouseExited(MouseEvent event) {}
> }
>
> /** The actual lines drawn are instances of the ColoredLine class. */
> class ColoredLine extends Line2D.Double
> { private static final long serialVersionUID = 149L;
> private final Color color;
> private final int thickness;
> public ColoredLine(double x,double y,double w,double h,Color color,int
> thickness)
> {
> super(x,y,w,h);
> this.color = color;
> this.thickness = thickness;
> }
>
> public Color getColor() {return color;}
> public int getThickness() {return thickness;}
> }
>

You need to follow the example I gave you a little closer.  I would 
extend JPanel rather than JFrame.  You can draw on the JPanel.  I would 
put the MouseListener into the JPanel rather than implementing it on the 
JPanel.  That you can do with a MouseAdapter and you don't have to 
create all of the methods.  You need to change the order in which you 
set up your GUI.  You do not want to make it visible until you have 
created all of the part.  You also need to wrap all Swing GUI creation 
code in EventQueue.invokeLater() so that it will be created on the Event 
Dispatch Thread.  The example I gave you shows that.

Note also that you rarely need the ContentPane of a JFrame anymore. 
JFrame.add() has been modified to add the Component to the JFrame's 
ContentPane.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;

public class test extends JPanel {
     private final Random random =
      new Random(System.currentTimeMillis());
     private BufferedImage image;
     private final java.util.List<ColoredShape> shapeList =
      new java.util.ArrayList<ColoredShape>();

     public test() {
         try {
             URL url =
              new URL("http://rabbitbrush.frazmtn.com/kittens.jpg");
             image = ImageIO.read(url);
             setPreferredSize(new Dimension(
              image.getWidth(),image.getHeight()));
         } catch (MalformedURLException murle) {
              // you need to catch these
         } catch (IOException ioe) {
         }

         addMouseListener(new MouseAdapter() {
             public void mousePressed(MouseEvent me) {
                 double w = random.nextDouble() * getWidth();
                 double h = random.nextDouble() * getHeight();
                 double x = me.getX() - w / 2.0;
                 double y = me.getY() - h / 2.0;
                 Color color = new Color(
                  random.nextInt(256),
                  random.nextInt(256),
                  random.nextInt(256));
                 ColoredShape shape = new ColoredShape(x,y,w,h,color);
                 shapeList.add(shape);
                 repaint();
             }
         });
     }

     // do all of your drawing in the overridden method paintComponent()
     public void paintComponent(Graphics g2d) {
         Graphics2D g = (Graphics2D)g2d;

         if (image != null)
             g.drawImage(image,0,0,null);

         for (ColoredShape shape : shapeList) {
             g.setColor(shape.getColor());
             g.fill(shape);
         }
     }

     class ColoredShape extends Ellipse2D.Double {
         private final Color color;

         public ColoredShape(double x,double y,double w,double h,
          Color color) {
             super(x,y,w,h);
             this.color = color;
         }

         public Color getColor() {
             return color;
         }
     }

     public static void main(String[] args) {
         // create GUI on EDT (event dispatch thread)
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 JFrame f = new JFrame();
                 f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 test t = new test();
                 f.add(t,BorderLayout.CENTER);
                 f.pack();
                 f.setVisible(true);
             }
         });
     }
}

[toc] | [prev] | [next] | [standalone]


#5033

From"A B" <@bleBaker.uk>
Date2012-02-17 18:07 +0000
Message-ID<4f3e977d$0$2966$fa0fcedb@news.zen.co.uk>
In reply to#5030
"Knute Johnson" <nospam@rabbitbrush.frazmtn.com> wrote on 16th February:
> On 2/16/2012 1:05 PM, A B wrote:
>> Sorry, I'm stumped, again. I really have been trying to sort it out
>> myself, but no luck. I've done it by adapting Knute Johnson's code
>> (which works fine in itself). Mine now defines a line and calls
>> repaint() as nice as you like, but there's no answer.
>>
>> I've chopped the code back to just the bits directly involved with the
>> drawing and sprinkled debugging statements everywhere, which established
>> that the bit that calls paintComponent() (via repaint() - that's right
>> isn't it?) is firing but paintComponent() itself isn't. Here's what's
>> left, if you're interested. Sorry if anyone finds it hard to read, I
>> don't know how you like it formatted.
>>
>> ------------------------
>> import java.awt.*;
>> import java.awt.event.*;
>> import java.awt.geom.*;
>> import java.util.*;
>> import javax.swing.*;
>>
>> public class Vectorine extends JFrame implements MouseListener
>> {
>> private static final long serialVersionUID = 159L;
>> // List to contain all the lines generated
>> private final java.util.List<ColoredLine> lineList = new
>> java.util.ArrayList<ColoredLine>();
>>
>> public static void main() {Vectorine v = new Vectorine();}
>>
>> public Vectorine()
>> {
>> super("Vectorine");
>> setSize(200, 200);
>> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
>> setVisible(true);
>>
>> // Set up window's initial contents
>> Container contentArea = getContentPane();
>> FlowLayout layout = new FlowLayout();
>> contentArea.setLayout(layout);
>> JPanel panelA = new JPanel();
>> panelA.addMouseListener(this);
>> contentArea.add(panelA);
>> setContentPane(contentArea);
>>
>> System.out.println("If you click anywhere in the box, 3 random lines
>> should appear in it.");
>> }
>>
>> public void paintComponent(Graphics g2d)
>> {
>> Graphics2D g = (Graphics2D)g2d;
>> System.out.println("Painting...");
>> for (ColoredLine hand : lineList)
>> {
>> System.out.println("Drawing line...");
>> BasicStroke pen = new BasicStroke(hand.getThickness());
>> g.setStroke(pen);
>> g.setColor(hand.getColor());
>> g.draw(hand);
>> }
>> }
>>
>> public void mouseClicked(MouseEvent event)
>> {
>> System.out.println("Mouse clicked");
>> double xcoord = 0, ycoord = 0;
>> for (int count=0; count<3; count++)
>> {
>> xcoord = 100 * Math.random();
>> ycoord = 100 * Math.random();
>> System.out.println("xcoord="+xcoord+", ycoord="+ycoord);
>> ColoredLine hand = new ColoredLine(0F, 0F, (float)xcoord, (float)ycoord,
>> Color.red, 2);
>> lineList.add(hand);
>> System.out.println("Calling repaint()...");
>> repaint();
>> }
>> }
>>
>> /** Blank methods to keep MouseListener happy. */
>> public void mousePressed(MouseEvent event) {}
>> public void mouseReleased(MouseEvent event) {}
>> public void mouseEntered(MouseEvent event) {}
>> public void mouseExited(MouseEvent event) {}
>> }
>>
>> /** The actual lines drawn are instances of the ColoredLine class. */
>> class ColoredLine extends Line2D.Double
>> { private static final long serialVersionUID = 149L;
>> private final Color color;
>> private final int thickness;
>> public ColoredLine(double x,double y,double w,double h,Color color,int
>> thickness)
>> {
>> super(x,y,w,h);
>> this.color = color;
>> this.thickness = thickness;
>> }
>>
>> public Color getColor() {return color;}
>> public int getThickness() {return thickness;}
>> }
>>
>
> You need to follow the example I gave you a little closer.  I would extend 
> JPanel rather than JFrame.  You can draw on the JPanel.  I would put the 
> MouseListener into the JPanel rather than implementing it on the JPanel. 
> That you can do with a MouseAdapter and you don't have to create all of 
> the methods.  You need to change the order in which you set up your GUI. 
> You do not want to make it visible until you have created all of the part. 
> You also need to wrap all Swing GUI creation code in 
> EventQueue.invokeLater() so that it will be created on the Event Dispatch 
> Thread.  The example I gave you shows that.
>
> Note also that you rarely need the ContentPane of a JFrame anymore. 
> JFrame.add() has been modified to add the Component to the JFrame's 
> ContentPane.

Thanks very much.  I'll try that.  Actually I thought I had done it in the 
JPanel, only I can't have, because I cut out the JPanel when I was 
simplifying, and here the MouseListener still is.  Daft.  I didn't realise 
the EventQueue stuff was necessary to the drawing routine, I think I thought 
it was for something else.
-- 
A. B.
><>
My e-mail address is zen177395 at  zendotcodotuk, though I don't check that 
account very often.
Post unto others as you would have them post unto you. 

[toc] | [prev] | [next] | [standalone]


#5040

FromKnute Johnson <nospam@knutejohnson.com>
Date2012-02-17 17:04 -0800
Message-ID<jhmte3$1tq$2@dont-email.me>
In reply to#5033
On 2/17/2012 10:07 AM, A B wrote:
> "Knute Johnson" <nospam@rabbitbrush.frazmtn.com> wrote on 16th February:
>> On 2/16/2012 1:05 PM, A B wrote:
>>> Sorry, I'm stumped, again. I really have been trying to sort it out
>>> myself, but no luck. I've done it by adapting Knute Johnson's code
>>> (which works fine in itself). Mine now defines a line and calls
>>> repaint() as nice as you like, but there's no answer.
>>>
>>> I've chopped the code back to just the bits directly involved with the
>>> drawing and sprinkled debugging statements everywhere, which established
>>> that the bit that calls paintComponent() (via repaint() - that's right
>>> isn't it?) is firing but paintComponent() itself isn't. Here's what's
>>> left, if you're interested. Sorry if anyone finds it hard to read, I
>>> don't know how you like it formatted.
>>>
>>> ------------------------
>>> import java.awt.*;
>>> import java.awt.event.*;
>>> import java.awt.geom.*;
>>> import java.util.*;
>>> import javax.swing.*;
>>>
>>> public class Vectorine extends JFrame implements MouseListener
>>> {
>>> private static final long serialVersionUID = 159L;
>>> // List to contain all the lines generated
>>> private final java.util.List<ColoredLine> lineList = new
>>> java.util.ArrayList<ColoredLine>();
>>>
>>> public static void main() {Vectorine v = new Vectorine();}
>>>
>>> public Vectorine()
>>> {
>>> super("Vectorine");
>>> setSize(200, 200);
>>> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
>>> setVisible(true);
>>>
>>> // Set up window's initial contents
>>> Container contentArea = getContentPane();
>>> FlowLayout layout = new FlowLayout();
>>> contentArea.setLayout(layout);
>>> JPanel panelA = new JPanel();
>>> panelA.addMouseListener(this);
>>> contentArea.add(panelA);
>>> setContentPane(contentArea);
>>>
>>> System.out.println("If you click anywhere in the box, 3 random lines
>>> should appear in it.");
>>> }
>>>
>>> public void paintComponent(Graphics g2d)
>>> {
>>> Graphics2D g = (Graphics2D)g2d;
>>> System.out.println("Painting...");
>>> for (ColoredLine hand : lineList)
>>> {
>>> System.out.println("Drawing line...");
>>> BasicStroke pen = new BasicStroke(hand.getThickness());
>>> g.setStroke(pen);
>>> g.setColor(hand.getColor());
>>> g.draw(hand);
>>> }
>>> }
>>>
>>> public void mouseClicked(MouseEvent event)
>>> {
>>> System.out.println("Mouse clicked");
>>> double xcoord = 0, ycoord = 0;
>>> for (int count=0; count<3; count++)
>>> {
>>> xcoord = 100 * Math.random();
>>> ycoord = 100 * Math.random();
>>> System.out.println("xcoord="+xcoord+", ycoord="+ycoord);
>>> ColoredLine hand = new ColoredLine(0F, 0F, (float)xcoord, (float)ycoord,
>>> Color.red, 2);
>>> lineList.add(hand);
>>> System.out.println("Calling repaint()...");
>>> repaint();
>>> }
>>> }
>>>
>>> /** Blank methods to keep MouseListener happy. */
>>> public void mousePressed(MouseEvent event) {}
>>> public void mouseReleased(MouseEvent event) {}
>>> public void mouseEntered(MouseEvent event) {}
>>> public void mouseExited(MouseEvent event) {}
>>> }
>>>
>>> /** The actual lines drawn are instances of the ColoredLine class. */
>>> class ColoredLine extends Line2D.Double
>>> { private static final long serialVersionUID = 149L;
>>> private final Color color;
>>> private final int thickness;
>>> public ColoredLine(double x,double y,double w,double h,Color color,int
>>> thickness)
>>> {
>>> super(x,y,w,h);
>>> this.color = color;
>>> this.thickness = thickness;
>>> }
>>>
>>> public Color getColor() {return color;}
>>> public int getThickness() {return thickness;}
>>> }
>>>
>>
>> You need to follow the example I gave you a little closer. I would
>> extend JPanel rather than JFrame. You can draw on the JPanel. I would
>> put the MouseListener into the JPanel rather than implementing it on
>> the JPanel. That you can do with a MouseAdapter and you don't have to
>> create all of the methods. You need to change the order in which you
>> set up your GUI. You do not want to make it visible until you have
>> created all of the part. You also need to wrap all Swing GUI creation
>> code in EventQueue.invokeLater() so that it will be created on the
>> Event Dispatch Thread. The example I gave you shows that.
>>
>> Note also that you rarely need the ContentPane of a JFrame anymore.
>> JFrame.add() has been modified to add the Component to the JFrame's
>> ContentPane.
>
> Thanks very much. I'll try that. Actually I thought I had done it in the
> JPanel, only I can't have, because I cut out the JPanel when I was
> simplifying, and here the MouseListener still is. Daft. I didn't realise
> the EventQueue stuff was necessary to the drawing routine, I think I
> thought it was for something else.

All GUI creation and almost all method calls to the Swing components 
must be done on the Event Dispatch thread.  The EventQueue.invokeLater() 
is used to cause that code to be run on the EDT.  After you do a few of 
these you'll get the hang of that.  It's really not difficult but the 
GUI may not work correctly if it isn't created on the EDT.

-- 

Knute Johnson

[toc] | [prev] | [next] | [standalone]


#5041

FromKnute Johnson <nospam@knutejohnson.com>
Date2012-02-17 17:08 -0800
Message-ID<jhmtmm$4m1$1@dont-email.me>
In reply to#5033
On 2/17/2012 10:07 AM, A B wrote:
> Thanks very much. I'll try that. Actually I thought I had done it in the
> JPanel, only I can't have, because I cut out the JPanel when I was
> simplifying, and here the MouseListener still is. Daft. I didn't realise
> the EventQueue stuff was necessary to the drawing routine, I think I
> thought it was for something else.

It's hard to learn to think in the language until you've seen it done 
several ways and then you've programmed it yourself over again.

I'm not sure what your program is going to do when it is finished but 
you can use the basic format that I gave to create lines or string lines 
together by following the mouse inputs.  You could add a popup menu to 
change color of the line or the style of the line as well.  The 
possibilities are unlimited once you've seen enough code to get an idea 
how to do it.

-- 

Knute Johnson

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.java.gui


csiph-web