использовать графику в paintComponent - PullRequest
0 голосов
/ 30 августа 2018

У меня есть следующий код, b представляет класс мяча из другого класса. Если я использую b.draw (g, true); Я не вижу результатов на экране, однако, если я использую g.fillOval (b.getX () - b.getRadius (), b.getY () - b.getRadius (), 2 * b.getRadius () , 2 * b.getRadius ()); Я получил хороший результат, я думал, что они оба используют графику и должны работать одинаково?

Заранее спасибо! Calum

public void paintComponent(Graphics g)
{
  super.paintComponent(g); // Paint the background
  g.setColor(Color.RED);
  g.drawString("Hello, Action!", xPos-100, yPos-200);
  // Not working
  b.draw(g,true);
  // Working
  //g.fillOval(b.getX() - b.getRadius(), b.getY() - b.getRadius(), 2* b.getRadius(), 2*b.getRadius());
}

Полный код:

import java.awt.Color;
import java.awt.Graphics;
public class Balloon
{
  private int xCenter, yCenter, radius;
  private Color color;

  /**
   * Constructs a balloon with the center at (0, 0),
   * radius 50, and blue color
   */
  public Balloon()
  {
    xCenter = 0;
    yCenter = 0;
    radius = 50;
    color = Color.BLUE;
  }

  /**
   * Constructs a balloon with a given center, radius and color
   * @param x x-coordinate of the center
   * @param y y-coordinate of the center
   * @param r radius of the balloon
   * @param c color of the balloon
   */
  public Balloon(int x, int y, int r, Color c)
  {
    xCenter = x;
    yCenter = y;
    radius = r;
    color = c;
  }

  /**
   * Returns the x-coordinate of the center.
   */
  public int getX()
  {
    return xCenter;
  }

  /**
   * Returns the y-coordinate of the center.
   */
  public int getY()
  {
    return yCenter;
  }

  /**
   * Returns the radius of this balloon.
   */
  public int getRadius()
  {
    return radius;
  }

  /**
   * Returns the color of this balloon.
   */
  public Color getColor()
  {
    return color;
  }

  /**
   * Returns the distance from a given point to the
   * center of this balloon.
   * @param x, y coordinates of the point
   */
  public double distance(int x, int y)
  {
    double dx = x - xCenter;
    double dy = y - yCenter;
    return Math.sqrt(dx*dx + dy*dy);
  }

  /**
   * Moves the center of this balloon to (x, y)
   * @param x x-coordinate of the new center
   * @param y y-coordinate of the new center
   */
  public void move(int x, int y)
  {
    xCenter = x;
    yCenter = y;
  }

  /**
   * Sets the radius of this balloon to r
   * @param r new radius
   */
  public void setRadius(int r)
  {
    radius = r;
  }

  /**
   * Returns true if a given point is strictly inside this balloon;
   * otherwise returns false
   * @param x, y coordinates of the point
   */
  public boolean isInside(int x, int y)
  {
    return distance(x, y) < 0.9 * radius;
  }

  /**
   * Returns true if a given point is on the border of this balloon;
   * otherwise returns false
   * @param x, y coordinates of the point
   */
  public boolean isOnBorder(int x, int y)
  {
    double d = distance(x, y);
    return d >= 0.9 * radius && d <= 1.1 * radius;
  }

  /**
   * Draws a solid circle if makeItFilled is true and
   * outline only if makeItFilled is false
   * @param g graphics context
   * @param makeItFilled draws a solid circle if true
   */
  public void draw(Graphics g, boolean makeItFilled)
  {
    g.setColor(color);
    if (makeItFilled)
      g.fillOval(xCenter - radius,
                 yCenter - radius, 2*radius, 2*radius);
    else
      g.drawOval(xCenter - radius,
                 yCenter - radius, 2*radius, 2*radius);
  }
}

Программа тестирования:

import java.awt.Graphics;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class FlyBalloon extends JPanel
                 implements ActionListener
{
  private int xPos, yPos;  // hold the coordinates of the message
  private Balloon b;

  public FlyBalloon(Balloon b)
  {
      this.b = b;
  }

  // Called automatically after a repaint request
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g); // Paint the background
    g.setColor(Color.RED);
    g.drawString("Hello, Action!", xPos-100, yPos-200);
    // Not working
    b.draw(g,true);
    // Working
    //g.fillOval(b.getX() - b.getRadius(), b.getY() - b.getRadius(), 2*b.getRadius(), 2*b.getRadius());
  }

  // Called automatically when the timer "fires"
  public void actionPerformed(ActionEvent e)
  {
    // Adjust the horizontal position of the message:
    yPos--;  // subtract 1
    if (yPos < -100)
      yPos = getHeight();
    this.b.move(xPos,yPos);

    repaint();
  }

  public static void main(String[] args)
  {
    JFrame window = new JFrame("Action Demo");

    // Set this window's location and size:
    // upper-left corner at 300, 300; width 400, height 600
    window.setBounds(300, 300, 400, 600);
    Balloon b = new Balloon(150,150,100,Color.RED);


    //  Create panel, a FlyBalloon object, which is a kind of JPanel:
    FlyBalloon panel = new FlyBalloon(b);
    panel.setBackground(Color.CYAN);  // the default color is light gray

    // Add panel to window:
    Container c = window.getContentPane();
    c.add(panel);

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    // Set the initial position of the message:
    panel.xPos = panel.getWidth() / 2;
    panel.yPos = panel.getHeight() ;

    // Create a Timer object that fires every 30 milliseconds;
    // attach it to panel so that panel "listens to" and
    // processes the timer events; start the timer:
    Timer clock = new Timer(30, panel);
    clock.start();
  }
}

1 Ответ

0 голосов
/ 01 сентября 2018

Если я использую b.draw (g, true); Я не вижу результатов на экране,

однако, если я использую g.fillOval (...), я получил хороший результат,

В обоих случаях я вижу, как текст и шарик движутся вверх по экрану, поэтому мне кажется, что он работает.

Однако, если это не работает для вас, вам нужно выполнить некоторую отладку, чтобы увидеть, в чем разница.

Когда я смотрю на код, я вижу:

  g.fillOval(xCenter - radius, yCenter - radius, 2*radius, 2*radius);

и

g.fillOval(b.getX() - b.getRadius(), b.getY() - b.getRadius(), 2*b.getRadius(), 2*b.getRadius());

Поэтому вместо выполнения всех ваших вычислений в вызове метода напишите ваш код как:

int x = xCenter - radius;
int y = yCenter - radius;
int size = 2 * radius;
System.out.println(x + " : " + y " + " : " + size);
g.fillOval(x, y, size, size);

Это позволяет отображать значения, используемые для рисования овала.

Сделайте то же самое для другого метода.

Затем вы можете сравнить результаты обоих подходов, чтобы увидеть, в чем разница.

...