在 JFrame 中使用坐标平面
//我正在尝试学习如何在java中绘制对象.我在这方面做得越来越好,但是一旦我在屏幕上看到图像,我就很难处理它.我输入的数字对形状的结果没有意义.至少对我来说他们没有.在代数中,如果你在 x 轴上增加一个数字,它会向右移动,如果你在 y 轴上增加一个数字,它会向上移动.那不是这里发生的事情.谁能向我解释这是如何工作的?我还是java新手,所以解释和细节越多越好.我想在暑假里每天抽出几个小时来学习 Java,但有时会有点令人沮丧.非常感谢任何帮助.
//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 in don't make sense to how the shapes are turning out. At least to me they don't. In algebra if you increase a number on the x axis it goes to the right and if you increase a number on the y axis it goes up. Thats not whats happening here. Can anyone explain to me how this works? I'm still new to java, so the more explanation and detail the better. I'm trying to take a couple of hours out a day over my summer to learn java and sometimes it gets a little frustrating. Any help is greatly appreciated.
推荐答案
这里的坐标
从屏幕的TOP LEFT SIDE
开始,随着你的增加X
的值,您将向 RIGHT SIDE
移动,但是当您增加 Y
的值时,您将移动 DOWNWARDS代码>.这是一个小示例程序,您可以更好地理解这一点,只需在任意位置单击即可.
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);
}
}
相关文章