Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

a Problem with java 2D

Thread view: 
York - 02 Nov 2007 18:12 GMT
Hi everybody,
i'm new to Java 2D and I have a Problem drawing a geometric primitive
on a JPanel.
I used getGraphics() to get the Graphics-Object of my JPanel, casted
it to Graphics2D, then drew a line on it und used myJPanel.repaint()
to update the JPanel.

But somehow I can't see the line I'v drawn and i can't figure it out
why .

the following is my code (without import statements):
......................................................................................................
public class NewJFrame extends JFrame {

   private JPanel pane = null;

   /** Creates new instance */
   public NewJFrame() {
       initComponents();

       // draw a line on JPanel
       Graphics2D canvas = (Graphics2D)pane.getGraphics();
       canvas.setPaint(Color.BLUE);
       canvas.draw(new Line2D.Float(1,1,111,111));
       pane.repaint();
   }

   private void initComponents() {
       Dimension min = new Dimension(300,300);
       setMinimumSize(min);

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
       pane = new JPanel();
       setContentPane(pane);
       pane.setBackground(new Color(255, 204, 255));
       pane.setForeground(new Color(51, 51, 255));
       pack();
   }

   public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               new NewJFrame().setVisible(true);
           }
       });
   }
}
......................................................................................................

Any help would be greatly appreicated, because I am deeply confused
and frustrated.
Daniel Pitts - 02 Nov 2007 18:39 GMT
> Hi everybody,
> i'm new to Java 2D and I have a Problem drawing a geometric primitive
[quoted text clipped - 47 lines]
> Any help would be greatly appreicated, because I am deeply confused
> and frustrated.

Repaint tells the panel to call the paint method, which will generally
erase everything you've painted on useing getGraphics().

The appropriate way to draw graphics is to create your own JComponent
subclass which override void paintComponent(Graphics g), and in that
method use the graphics object thats passed in.

Generally, you can cast Graphics2d g2d = (Graphics2d)g; and use the
newer Java 2d API.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Knute Johnson - 02 Nov 2007 19:27 GMT
>> Hi everybody,
>> i'm new to Java 2D and I have a Problem drawing a geometric primitive
[quoted text clipped - 58 lines]
> Generally, you can cast Graphics2d g2d = (Graphics2d)g; and use the
> newer Java 2d API.

And here is a simple example;

http://knutejohnson.com/imageio.html

Signature

Knute Johnson
email s/nospam/knute/

Andrew Thompson - 02 Nov 2007 19:29 GMT
(OP)
>> the following is my code (without import statements):

..hmm.  That code was frustratingly close to being an SSCCE*.

>The appropriate way to draw graphics is to create your own JComponent
>subclass which override void paintComponent(Graphics g), and in that
>method use the graphics object thats passed in.

..or to put that an SSCCE way.

<sscce>
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class NewJFrame extends JFrame {

  private JPanel pane = null;

  /** Creates new instance */
  public NewJFrame() {
      initComponents();
  }

  private void initComponents() {
      Dimension min = new Dimension(300,300);
      setMinimumSize(min);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      pane = new JPanel(){
          public void paintComponent(Graphics g) {
              super.paintComponent(g);
             // draw a line on JPanel
             Graphics2D canvas = (Graphics2D)g;
             canvas.setPaint(Color.BLUE);
             canvas.draw(new
               Line2D.Float(
                 1,1,
                 getWidth()/2,
                 getHeight()/2));
           }
          };
      setContentPane(pane);
      pane.setBackground(new Color(255, 204, 255));
      pane.setForeground(new Color(51, 51, 255));
      pack();
  }

  public static void main(String args[]) {
      EventQueue.invokeLater(new Runnable() {
          public void run() {
              new NewJFrame().setVisible(true);
          }
      });
  }
}
</sscce>

* <http://www.physci.org/codes/sscce.html>

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Chris ( Val ) - 03 Nov 2007 09:20 GMT
> (OP)
>
> >> the following is my code (without import statements):
>
> .hmm.  That code was frustratingly close to being an SSCCE*.

[snip]

Did you test your SSCCE?

--
Chris
Andrew Thompson - 03 Nov 2007 09:53 GMT
>> (OP)
>>
[quoted text clipped - 5 lines]
>
>Did you test your SSCCE?

Yep.

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Chris ( Val ) - 03 Nov 2007 09:57 GMT
> >> (OP)
>
[quoted text clipped - 7 lines]
>
> Yep.

Ok, next question :-)

Is the code you pasted here, actually the code you tested?

The reason I ask is because your SSCCE does not compile for me.

--
Chris
Chris ( Val ) - 03 Nov 2007 10:01 GMT
> > >> (OP)
>
[quoted text clipped - 13 lines]
>
> The reason I ask is because your SSCCE does not compile for me.

Oop's, I meant there are 2 warnings, sorry :-)

--
Chris
Lew - 03 Nov 2007 15:32 GMT
>> The reason I ask is because your SSCCE does not compile for me.
>
> Oop's [sic], I meant there are 2 warnings, sorry :-)

and they are ...?

Signature

Lew

Chris ( Val ) - 04 Nov 2007 13:08 GMT
> >> The reason I ask is because your SSCCE does not compile for me.
>
> > Oop's [sic], I meant there are 2 warnings, sorry :-)
>
> and they are ...?

My apologies for not posting them.

Compiled using version: "1.6.0_02"

Here are the two warning I received:

C:\Java\classes\NewJFrame.java:19: warning: [serial] serializable
class <anonymous NewJFrame$1> has no definition of serialVersionUID
      pane = new JPanel(){
                         ^
C:\Java\classes\NewJFrame.java:5: warning: [serial] serializable class
NewJFrame has no definition of serialVersionUID
public class NewJFrame extends JFrame {
      ^
2 warnings

Also note the placement of the parenthesis, in the following piece of
code:

    EventQueue.invokeLater(new Runnable()
     {
          public void run()
           {
            new NewJFrame().setVisible(true);
           }
     });

Do you see a problem here?

--
Chris
Lew - 04 Nov 2007 14:19 GMT
>>>> The reason I ask is because your SSCCE does not compile for me.
>>> Oop's [sic], I meant there are 2 warnings, sorry :-)
[quoted text clipped - 15 lines]
>        ^
> 2 warnings

It's a warning instead of an error because Serializable classes don't need an
explicit serialVersionUID; in its absence Java generates one for you.  It's a
warning at all because leaving it at the default can cause you maintenance pain.

Have you read the Javadocs for java.io.Serializable?  They discuss this member
variable there.  Also, Joshua Bloch's seminal /Effective Java/ covers
Serialization in detail.

To implement Serializable is a solemn responsibility that a lot of people hack
through, then wonder why they have trouble later.  It exposes details of
implementation, violating OO encapsulation, and locks in aspects of the class
design.  Failing to account for that causes trouble.  It can be horridly
inefficient, unless you take care.  You can have trouble with modifications to
a class if it is enhanced (refactoring, additional features, ...).  It's
actually a fair amount of work to make something Serializable correctly.

> Also note the placement of the parenthesis, in the following piece of
> code:
[quoted text clipped - 8 lines]
>
> Do you see a problem here?

No.  What is your point?

Signature

Lew

Chris ( Val ) - 04 Nov 2007 14:31 GMT
> >>>> The reason I ask is because your SSCCE does not compile for me.
> >>> Oop's [sic], I meant there are 2 warnings, sorry :-)
[quoted text clipped - 17 lines]
>
> It's a warning instead of an error

Yes, that's what I said (corrected), in my follow up.

>because Serializable classes don't need an
> explicit serialVersionUID; in its absence Java generates one for you.  It's a
> warning at all because leaving it at the default can cause you maintenance pain.

I see, thank you.

> Have you read the Javadocs for java.io.Serializable? They discuss this member
> variable there.  Also, Joshua Bloch's seminal /Effective Java/ covers
> Serialization in detail.

No, I have not looked closely into the Serializable interface yet,
but I will in good time.

> To implement Serializable is a solemn responsibility that a lot of people hack
> through, then wonder why they have trouble later.  It exposes details of
[quoted text clipped - 3 lines]
> a class if it is enhanced (refactoring, additional features, ...).  It's
> actually a fair amount of work to make something Serializable correctly.

Thanks again, I will check it out in good time.

> > Also note the placement of the parenthesis, in the following piece of
> > code:
[quoted text clipped - 10 lines]
>
> No.  What is your point?

Well, my point is that it looks missplaced?

--
Chris
Chris ( Val ) - 04 Nov 2007 14:58 GMT
[snip]

> > Also note the placement of the parenthesis, in the following piece of
> > code:
[quoted text clipped - 10 lines]
>
> No.  What is your point?

Perhaps the following is a little more obvious?

    EventQueue.invokeLater( new Runnable()
     {
      public void run(){new NewJFrame().setVisible(true);}
     }

     );
    ^^^--------?

--
Chris
Lew - 04 Nov 2007 15:25 GMT
> Perhaps the following is a little more obvious?
>
[quoted text clipped - 5 lines]
>       );
>      ^^^--------?

Matches the opening paren of the invokeLater method.

Signature

Lew

Chris ( Val ) - 04 Nov 2007 15:46 GMT
> > Perhaps the following is a little more obvious?
>
[quoted text clipped - 7 lines]
>
> Matches the opening paren of the invokeLater method.

Yes, I realise that.

What I find odd, is that there is a new scope
{ /* more stuff */ }, prior to the closing parenthesis.

IOW, is something like:

void Foo( new Bar() { System.out.println( "In the body of new
Bar" ); } );

...legal in Java?

--
Chris
Lew - 04 Nov 2007 16:29 GMT
>>> Perhaps the following is a little more obvious?
>>>      EventQueue.invokeLater( new Runnable()
[quoted text clipped - 6 lines]
>
> Yes, I realise that.

Then why did you highlight the closing paren?

> What I find odd, is that there is a new scope
> { /* more stuff */ }, prior to the closing parenthesis.

It's a class definition.

> IOW, is something like:
>
> void Foo( new Bar() { System.out.println( "In the body of new
> Bar" ); } );
>
> ....legal in Java?

No, because you are not defining a class inside the braces.  IOW, the
System.out.println() has to happen inside a method.  Also, you don't declare
the anonymous class in the declaration of the calling method (Foo, here, which
should have used a lower-case first letter in its name), but in its invocation.

<untested>
public interface Bar
{
  public void do();
}

public class Foo
{
 public void foo( Bar bar )
 {
   bar.do();
 }

 public static void main( String [] args )
 {
   Foo foo = new Foo();
   foo.foo( new Bar()
    {
     public void do()
     {
      System.out.println( "In the body of new Bar" );
     }
    }
   );
 }
}
</untested>

Research anonymous classes.

<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.9.5>

<http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html>
gives this a brief mention.

One of the best sites around for learning about Java features is mindprod.com.
<http://mindprod.com/jgloss/anonymousclasses.html>

Signature

Lew

Chris ( Val ) - 06 Nov 2007 14:13 GMT
> >>> Perhaps the following is a little more obvious?
> >>>      EventQueue.invokeLater( new Runnable()
[quoted text clipped - 8 lines]
>
> Then why did you highlight the closing paren?

Because I thought it was a problem with the syntax, and
I did (I thought clearly) enquire if it was legal syntax.

> > What I find odd, is that there is a new scope
> > { /* more stuff */ }, prior to the closing parenthesis.
[quoted text clipped - 10 lines]
> No, because you are not defining a class inside the braces.  IOW, the
> System.out.println() has to happen inside a method.  

Ok, that wasn't meant to be a perfect example, that's why I said:
 "something like..."

> Also, you don't declare
> the anonymous class in the declaration of the calling method (Foo, here, which
> should have used a lower-case first letter in its name), but in its invocation.

[snip - example that used a java keyword :-)]

> Research anonymous classes.

[snip]

Thank you.

I will check it out, as I had not come across such a syntax before.

> One of the best sites around for learning about Java features is mindprod.com.
> <http://mindprod.com/jgloss/anonymousclasses.html>

Yes, Roedy has done a great job and is very helpful.

--
Chris
Andrew Thompson - 04 Nov 2007 01:07 GMT
>> >> (OP)
>>
[quoted text clipped - 5 lines]
>
>Is the code you pasted here, actually the code you tested?

Yep.

>The reason I ask is because your SSCCE does not compile for me.

(sigh)  I was hoping you could take my first answer as a hint.

I'll try another approach.

The code I posted was successfully locally compiled and
run.  It shows a slightly different thing to what the OP
wants, since the line will change if the JFrame is resized,
but that is less boring than a static line, and I wanted to
demonstrate that it would be redrawn when resized.

I just copied the code I posted, back into my Java
environment and compiled it 'fresh', to check there
was no line-wrap  between when I first wrote it in
my editor, to when it arrived back there (via. usenet).

It compiled cleanly again.

So, we might go 'round & round'* with you making some
(semi)cryptic comment and me replying with 'one word'
answers to try and draw more detail out, or you might help
the thread along by stating *exactly what it is about
compiling the code that causes a problem for you.*

If, for example, you are getting ...

D:\NewJFrame.java:24: cannot find symbol
symbol  : variable BLUE
location: class java.awt.Color
            canvas.setPaint(Color.BLUE);

..then upgrade from 1.3, for pities sake!

For anything else, please *state the problem* specifically.

* But no, not for long - I have a short attention span.

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Chris ( Val ) - 04 Nov 2007 14:15 GMT
> >> >> (OP)
>
[quoted text clipped - 11 lines]
>
> (sigh)  I was hoping you could take my first answer as a hint.

No need to "sigh".

Surely you read my latter reply, right?

[snip]

> I just copied the code I posted, back into my Java
> environment and compiled it 'fresh', to check there
> was no line-wrap  between when I first wrote it in
> my editor, to when it arrived back there (via. usenet).
>
> It compiled cleanly again.

What version of compiler did you use?
I used: "1.6.0_02"

Here are the two warnings that were produced:

C:\Java\classes\NewJFrame.java:19: warning: [serial] serializable
class <anonymous NewJFrame$1> has no definition of serialVersionUID
      pane = new JPanel(){
                         ^
C:\Java\classes\NewJFrame.java:5: warning: [serial] serializable class
NewJFrame has no definition of serialVersionUID
public class NewJFrame extends JFrame {
      ^
2 warnings

> So, we might go 'round & round'* with you making some
> (semi)cryptic comment and me replying with 'one word'
> answers to try and draw more detail out, or you might help
> the thread along by stating *exactly what it is about
> compiling the code that causes a problem for you.*

Sure, but note that "communication" works both ways, and
a solitary 'yep' does nothing to help the thread along.

--
Chris
Lew - 04 Nov 2007 14:20 GMT
> I used [Java version] "1.6.0_02"

There is a security flaw in that version that was fixed in Java 6 update 3.

Signature

Lew

Chris ( Val ) - 04 Nov 2007 14:36 GMT
> > I used [Java version] "1.6.0_02"
>
> There is a security flaw in that version that was fixed in Java 6 update 3.

Thank you for the information.

I have the latest version on my other computer,
and I am installing it on this one as we speak.

--
Chris
Roedy Green - 03 Nov 2007 18:48 GMT
>     canvas.draw(new Line2D.Float(1,1,111,111));

that is not how it is used.  See
http://mindprod.com/jgloss/canvas.html

all your drawing goes on in paintComponent.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.