Reputation: 431
Heres an example of a method to draw 1 line passing in two points
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(0,60,100,60);
}
Im trying to pass in a constructor for the points but when I go to run it in main I cannot figure what value I should pass in for comp when I call paintComponent
public class DrawLines{
public void paintComponent(Graphics comp,int x0, int y0, int x1, int y1) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawLine(x0,y0,x1,y1);
}
public static void main(String[]args){
drawLine(?,100,200,200,300);
}
}
What should I pass in at the ?
Upvotes: 0
Views: 916
Reputation: 285405
You'll want to give your class two Point fields, either that or four int fields, x1, y1, x2, y2, pass the values used to initialize these fields in your constructor, and then most important, use the value held in these fields when doing your drawing.
e.g.,
import javax.swing.*;
import java.awt.*;
public class LinePanel extends JPanel {
private Point p1; // java.awt.Point objects
private Point p2;
// TODO: create constructor that accepts
// and updates the two points
public void paintComponent(Graphics g) {
super.paintComponent(g); // don't forget this!
// TODO: Change the method below so that it uses
// the two points to do the drawing with
// rather than use hard coded magic numbers.
g.drawLine(0, 0, 90, 90);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public static void main(String args[]) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(new LinePanel()); // TODO: add parameters to constructor call.
// jf.setSize(500, 500);
jf.pack();
jf.setVisible(true);
}
}
Upvotes: 3
Reputation: 11999
You need a Graphics
(will normally be a Graphics2D
instance when using Swing) object, which gives you some context to actually draw with. Take a look at your main class... You want to draw a line, but what do you have to draw on? There isn't magically gonna be some window or canvas that pops up to draw on, you'll need to set that stuff up.
I suggest checking the Java Swing tutorial. That is, if you're already reasonably well versed in Java. If not, make sure your Java knowledge is first brought up to a decent level.
Upvotes: 4