Using the coordinate plane in the JFrame

后端 未结 1 1756
悲&欢浪女
悲&欢浪女 2020-12-10 08:08

//I am trying to learn how to draw objects in java. I\'m getting better at it, but once I get an image on the screen I am having trouble manipulating it. The numbers I put i

相关标签:
1条回答
  • 2020-12-10 09:05

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题