Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to Draw a Line in Java?

 
Avin Sinanan
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok how does one draw a simple line in java..
here is the cod ei have so far... i can draw a line but i am looking for a different method to draw it.. take a look at my code... its very short
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
class AvinLine
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel pane = new JPanel();
Line2D myLine = new Line2D.Double(5,5,100,100);

frame.getContentPane().add(pane);
frame.setSize(300,300);
frame.pack();
frame.setVisible(true);
}
}
Ok how do i draw the line without creating another class .. and the JPanel and JFrame must be in the same class.. I am trying to avoid making a new clas that extends JPanel. I do not want to add another class. The line must be added within this class. And i am also trying to avoid the "paint(Graphics g)" method. Is there anyway to add the line to the JPanel and then add the panel to the JFrame.
Because I find it dificult to believe that Java is such a powerful language that you have to call a "paint(Graphics g)" method and create another class just to draw a simple line.
Thanks for the help in advance..
 
Sean MacLean
author
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avin,
To draw to the screen, you must have a graphics context (object). To get this object to do it's work you have use it to draw a line (using it's draw line method). Perhaps you should find a good primer tutorial on Java's awt api in order to get a better understanding of the underlying mechanisms behind it's implementation. This will go long way to helping you answer many of your questions.
Sean
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, don't know if you specifically need to draw a line a specific way, but as long as it can go entirely accross your panel, try using a Seperator(). It worked great for me.

------------------
Happy Coding,
Gregg Bolinger
 
Colin Kenworthy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would this work, a sort of inner class ?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic