This is the main java file that gets the panel and puts it in the JFrame
package graph;
import javax.swing.JFrame;
public class Graph {
public static void main(String[] args) {
JFrame frame = new JFrame("Graph line between 2 points");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new graphPanel());
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
This is the graphPanel class
package graph;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class graphPanel extends JPanel{
private int p1X, p1Y, p2X, p2Y;
public graphPanel()
{
setPreferredSize(new Dimension(500,500));
setBackground(Color.BLACK);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
g.drawLine(250, 0, 250, 500);
g.drawLine(0, 250, 500, 250);
g.drawString("Y", 275, 15);
g.drawString("X", 485, 275);
g.drawLine(240,25,260,25);
g.drawLine(240,50,260,50);
g.drawLine(240,75,260,75);
g.drawLine(240,100,260,100);
g.drawLine(240,125,260,125);
g.drawLine(240,150,260,150);
g.drawLine(240,175,260,175);
g.drawLine(240,200,260,200);
g.drawLine(240,225,260,225);
g.drawLine(240,275,260,275);
g.drawLine(240,300,260,300);
g.drawLine(240,325,260,325);
g.drawLine(240,350,260,350);
g.drawLine(240,375,260,375);
g.drawLine(240,400,260,400);
g.drawLine(240,425,260,425);
g.drawLine(240,450,260,450);
g.drawLine(240,475,260,475);
g.drawLine(25,240,25,260);
g.drawLine(50,240,50,260);
g.drawLine(70,240,70,260);
g.drawLine(100,240,100,260);
g.drawLine(125,240,125,260);
g.drawLine(150,240,150,260);
g.drawLine(175,240,175,260);
g.drawLine(200,240,200,260);
g.drawLine(225,240,225,260);
g.drawLine(275,240,275,260);
g.drawLine(300,240,300,260);
g.drawLine(325,240,325,260);
g.drawLine(350,240,350,260);
g.drawLine(375,240,375,260);
g.drawLine(400,240,400,260);
g.drawLine(425,240,425,260);
g.drawLine(450,240,450,260);
g.drawLine(475,240,475,260);
g.setColor(Color.BLUE);
g.setFont(new Font("Helvetica", Font.PLAIN, 18));
g.drawString("Point 1: ( " + p1X + ", " + p1Y + " )", 300, 400);
g.drawString("Point 2: ( " + p2X + ", " + p2Y + " )", 300, 450);
Random rand = new Random();
p1X = rand.nextInt(500)+0;
p1Y = rand.nextInt(500)+0;
p2X = rand.nextInt(500)+0;
p2Y = rand.nextInt(500)+0;
g.setColor(Color.WHITE);
g.drawLine(p1X, p1Y, p2X, p2Y);
repaint();
}
}
Click below to see video of the program
No comments:
Post a Comment