代码之家  ›  专栏  ›  技术社区  ›  user2329174

java图形变量给出错误值

  •  1
  • user2329174  · 技术社区  · 6 年前

    您好,我想知道是否有人可以帮助我,我已将2个值x1、y1声明为120,并尝试在以下方法中使用它们:

    private void drawDot(int x, int y, Graphics2D twoD) {
    
        twoD.fillOval(x-50, y-50, 100, 100);
    
    }
    

    然而,当我使用drawDot(120120,twoD)时,与手动使用时相比,它在错误的位置绘制填充的椭圆形

    twoD.fillOval(70,70,100,100);
    

    这两条语句不应该做完全相同的事情吗?我有什么遗漏吗?我添加了一张图片来展示这个问题,左边的椭圆形是用drawDot方法绘制的椭圆形,右边的椭圆形是在正确位置的椭圆形。如果有人有任何建议,将不胜感激。谢谢

    click this link to see how both ovals are drawn

    整个班级:

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class DieFace extends JPanel {
    
    int x1,y1 = 120;
    int x2,y2 = 300;
    int x3,y3 = 480;
    
    private BufferedImage bufferedImage;
    
    public DieFace() {
    
        this.init();
        this.frameInit();       
        updateVal(1);
    
    }
    
    private void init() {
    
        this.setPreferredSize(new Dimension(600,600));
    
    }
    
    
    private void frameInit() {
    
        JFrame window = new JFrame("Dice Simulation");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setContentPane(this);
        window.pack();
        window.setVisible(true);
        window.setLocationRelativeTo(null);
    
    }
    
    public void paintComponent(Graphics g) {
    
        Graphics2D twoD = (Graphics2D) g;
        twoD.drawImage(bufferedImage,0,0,null);
    
    }
    
    private void drawDot(int x, int y, Graphics2D twoD) {
    
        twoD.fillOval(x-50, y-50, 100, 100);
    
    }
    
    public void updateVal(int dieRoll) {
    
        bufferedImage = new BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);
        Graphics2D twoD = bufferedImage.createGraphics();
        twoD.setColor(Color.WHITE);
        twoD.fillRect(0, 0, 600, 600);
        twoD.setColor(Color.BLACK);
    
        if(dieRoll==1) {
    
            drawDot(x1,y1,twoD);
            twoD.fillOval(70, 70, 100, 100);
    
        }
    
        repaint();
    
    }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   user3437460    6 年前

    这两条语句不应该做完全相同的事情吗?我有什么遗漏吗?

    因为您在上的变量初始化时出错 x1 ,则, y1 :

    int x1,y1 = 120;    //This means x1 = 0, y1 = 120
    

    你真正想要的是:

    int x1 = 120, y1 = 120;
    

    自从 x1 调用时不是120

    drawDot(x1,y1,twoD);    
    

    drawDot(0, 120, twoD); 正在调用

    因此,两个省略号将出现在相同的y轴上,但在x轴上不同。