Sotnam96
Sotnam96

Reputation: 63

Java Draw Lines in one Frame

I try to do a very simple thing.. at class Main i draw 2 lines for the Coordinate System.. and at class userPaint i draw 1 line from x1 y1 x2 y2 (already initialised). The problem is that the 3 lines (the coordinate system and the x1y1x2y2 line) are not in the same window/frame. The compiler creates 2 windows... how can i fix that?

Main class:

import static javax.swing.JFrame.EXIT_ON_CLOSE;
import java.awt.*;
import javax.swing.*;

public class Main extends JFrame {

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(20, 80, 20, 200);
        g.drawLine(20, 200, 140, 200);
    }

    public Main(String title){
        super(title);
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        Main main = new Main("Graph");
        userPaint up = new userPaint();
    }
}

userPaint class:

import java.awt.*;
import javax.swing.*;

public class userPaint extends JFrame {
    int x1, y1, x2, y2;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(x1, y1, x2, y2);
    }

    public userPaint(){
        //Gives 4 numbers for points to drawline. Assume that the x1,y1,x2,y2 are given by Scanner.. but im gonna initialize
        x1 = 200;
        y1 = 200;
        x2 = 300;
        y2 = 300;
        setSize(800, 600);
        setVisible(true);
    }
}

Upvotes: 1

Views: 4534

Answers (1)

copeg
copeg

Reputation: 8348

  1. Don't paint directly to a JFrame, rather paint to a JPanel which you can add the the content pane of a JFrame via the JFrame's add method
  2. Painting in (1) should be done by overriding the paintComponent method (not the paint method).

For example:

public class Painter extends JPanel{

    public Painter(){

    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawLine(20, 80, 20, 200);
        g.drawLine(20, 200, 140, 200);
        g.drawLine(x1, y1, x2, y2);
    }
}

...
JFrame frame = new JFrame("Title");
frame.add(new Painter());

draw 2 lines for the Coordinate System

You mention a coordinate system, so you may wish to offset the x1..y2 values with those of the coordinate system so the drawn line falls within the bounds of the axis. As an example:

        g.drawLine(20, 80, 20, 200);//y-axis
        g.drawLine(20, 200, 140, 200);//x-axis
        g.drawLine(x1 + 20, 200 - y1, x2 + 20, 200 - y2);//offset by coordinate system

The above offsets the x-values by the position of the of the x-axis, and y-values by the position of the y-axis (negatively so the plot is not inverted) - assuming these values are not offset already, and their pixel positions are relative to the bounds of the axis.

One final note: class names should be uppercase

Upvotes: 5

Related Questions