Using a coordinate plane in a JFrame

// I'm trying to learn how to draw objects in java. I feel better, but as soon as I get the image on the screen, I have problems with manipulating it. The numbers that I insert do not make sense in how the shapes are formed. At least I don't like it. In algebra, if you increase the number along the x axis, it goes to the right, and if you increase the number along the y axis, it increases. This is not what is happening here. Can someone explain to me how this works? I'm still new to java, so the more explanations and details, the better. I try to spend a couple of hours during the day over my summer to learn java, and sometimes it is a little frustrating. Any help is appreciated.

+5
source share
1 answer

Co-ordinatesStart here from the TOP LEFT SIDEscreen, because as you increase the value, Xyou will go to RIGHT SIDE, although as you increase the value, Yyou will move DOWNWARDS. Here is a small example of the program so that you understand it a little better, just 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);
    }
}
+6
source

All Articles