Rotating Coordinate Plane for Data and Text in Java

Using the coordinate plane in the JFrame

Here the Co-ordinates start from the TOP LEFT SIDE of the screen, as as you increase value of X, you will move towards RIGHT SIDE, though as you increase the value of Y, you will move DOWNWARDS. Here is a small example Program for you to understand this a bit better, simply click on it anywhere.

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

public class DrawingExample
{
private int x;
private int y;
private String text;
private DrawingBase canvas;

private void displayGUI()
{
JFrame frame = new JFrame("Drawing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

canvas = new DrawingBase();
canvas.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
text = "X : " + me.getX() + " Y : " + me.getY();
x = me.getX();
y = me.getY();
canvas.setValues(text, x, y);
}
});

frame.setContentPane(canvas);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DrawingExample().displayGUI();
}
});
}
}

class DrawingBase extends JPanel
{
private String clickedAt = "";
private int x = 0;
private int y = 0;

public void setValues(String text, int x, int y)
{
clickedAt = text;
this.x = x;
this.y = y;
repaint();
}

public Dimension getPreferredSize()
{
return (new Dimension(500, 400));
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(clickedAt, x, y);
}
}

Cartesian Plane in Java

Your Point class doesn't have access to the Graphics2D object of the CartesianPanel.

You should move the functionality of your FromCartToPix and DrawPoint methods to the CartesionPanel. This way you can actually draw the points and you separate the data (Point) from the UI (the CartesionPanel).

// add in CartesionPanel
private List<Point> points = new ArrayList<>();

public void drawPoint(Point point) {
points.add(point);
repaint();
}

private void drawPointOnPanel(Point point, Graphics g) {
final int pointDiameter = 5;
final int x = X_AXIS_FIRST_X_COORD + (point.x * xLength) - pointDiameter / 2;
final int y = Y_AXIS_SECOND_Y_COORD - (point.y * yLength) - pointDiameter / 2;
g.fillOval(x, y, pointDiameter, pointDiameter);
}

public void paintComponent(Graphics g) {
// existing code ...

// draw points
points.forEach(p -> drawPointOnPanel(p, g))
}

In your main function you could draw Points by:

CartesianFrame frame = new CartesianFrame();
frame.showUI();

frame.panel.drawPoint(new Point(3, 4));


Related Topics



Leave a reply



Submit