Java在方法中使用Graphics

时间:2014-05-02 18:32:24

标签: java swing jframe mouselistener drawimage

大家好,我是Java的新手;我环顾四周,无法找到这个问题的答案。你有机会帮助我吗?

这是我想要实现的一个例子。

public class FrameWork extends JFrame implements MouseListener {
... //Irrelevant to the question code
public void mouseClicked(MouseEvent e){

int x = e.getX();
int y = e.getY();
if (x==1 && y==1){
// This is where and when I want to draw GFXDice
}
}}

现在是另一个类,所有导入都是为了便于阅读。

public class Board extends JPanel{
Image GFXDice1; 
public Board() {
ImageIcon Dice1;
Dice1 = new ImageIcon(this.getClass().getResource("GFX/Dice1"));
GFXDice1 = Dice1.getImage();
}

现在是图形部分

public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(GFXDice, 100, 100, null);
}

现在提出问题 - 我想使用Class FrameWork中Class Board的方法 - 但不能让它工作 - 任何想法?我向任何有想法的人提供了数以亿计的善业。

1 个答案:

答案 0 :(得分:3)

进行大多数Swing绘图的一般方法是通过被动图形。这意味着:

  • 在JPanel或JComponent的paintComponent(Graphics g)方法中执行绘图本身。
  • 在MouseListener中更改类的某些字段的状态。在mouseClicked方法中,您设置了某些本地变量的状态,我建议您改为创建x和y字段,而不是本地字段。
  • 然后当鼠标监听器完成更改时,请在JPanel上调用repaint()
  • 然后在paintComponent方法中,使用在鼠标侦听器中更改的那些字段来进行绘制。
  • 不要忘记在paintComponent覆盖中调用super的paintComponent方法。
  • 不要忘记阅读有关Swing Graphics的教程以获得优点。

修改

例如,请查看我为another recent question的答案创建的小型图形程序。

绘图发生在扩展JPanel的主类SpaceShip中。我为我的鼠标侦听器添加了一个匿名的内部MouseAdapter类,在MouseAdapter内部,我调用了一个名为moveIt的方法,传入了MouseEvent对象。

   MouseAdapter myMouseAdapter = new MouseAdapter() {
     public void mousePressed(MouseEvent evt) {
        moveIt(evt);
        count = count + 1;
     }

     @Override
     public void mouseDragged(MouseEvent evt) {
        moveIt(evt);
     }
  };
  addMouseListener(myMouseAdapter);
  addMouseMotionListener(myMouseAdapter);
}

所有moveIt(MouseEvent evt)所做的就是更改两个字段myX和myY的状态,然后在当前类上调用repaint()

public void moveIt(MouseEvent evt) {
  myY = evt.getY() - sprite.getHeight() / 2;
  myX = evt.getX() - sprite.getWidth() / 2;
  repaint();
}

然后在类的paintComponent方法中,我首先调用super的paintComponent以允许它擦除任何以前的旧的过时图像,然后我绘制背景图像,背景,然后我绘制一个使用的精灵myX和myY变量告诉它在哪里绘制,然后我在由JPanel大小决定的位置绘制一些黄色矩形:

protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  font1 = new Font("Serif", Font.BOLD, 36);
  g.drawImage(background, 0, 0, this);
  g.drawImage(sprite, myX, myY, this);
  g.setColor(Color.yellow);
  int rectCount = 10;
  int height = getHeight() / rectCount;
  int width = 272;
  int x = getWidth() - width;
  for (int i = 0; i < rectCount; i++) {
     int y = i * height;
     g.drawRect(x, y, width, height);
  }
  g.setFont(font1);
  g.drawString(Integer.toString(count), 500, 100);
}

整件事看起来像这样:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.io.IOException;
import java.net.URL;
import java.lang.String;
import java.awt.Font;

@SuppressWarnings("serial")
public class SpaceShip extends JPanel {
   private static final String BACKGROUND_PATH = "http://www.thatsreallypossible.com/"
         + "wp-content/uploads/2012/12/Space-Colonialisation.jpg";
   private static final String SPRITE_PATH = "http://www.pd4pic.com/"
         + "images250_/ufo-flying-saucer-spacecraft-spaceship-alien.png";

   private Font font1;
   int myX = 100;
   int myY = 400;
   int count = 0;
   private BufferedImage background;
   private BufferedImage sprite;

   public SpaceShip() throws IOException {
      URL backgroundUrl = new URL(BACKGROUND_PATH);
      URL spriteUrl = new URL(SPRITE_PATH);
      background = ImageIO.read(backgroundUrl);
      sprite = ImageIO.read(spriteUrl);

      MouseAdapter myMouseAdapter = new MouseAdapter() {
         public void mousePressed(MouseEvent evt) {
            moveIt(evt);
            count = count + 1;
         }

         @Override
         public void mouseDragged(MouseEvent evt) {
            moveIt(evt);
         }
      };
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   public Dimension getPreferredSize() {
      if (background != null) {
         return new Dimension(background.getWidth(), background.getHeight());
      }
      return super.getPreferredSize();
   }

   public void moveIt(MouseEvent evt) {
      myY = evt.getY() - sprite.getHeight() / 2;
      myX = evt.getX() - sprite.getWidth() / 2;
      repaint();
   }


   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      font1 = new Font("Serif", Font.BOLD, 36);
      g.drawImage(background, 0, 0, this);
      g.drawImage(sprite, myX, myY, this);
      g.setColor(Color.yellow);
      int rectCount = 10;
      int height = getHeight() / rectCount;
      int width = 272;
      int x = getWidth() - width;
      for (int i = 0; i < rectCount; i++) {
         int y = i * height;
         g.drawRect(x, y, width, height);
      }
      g.setFont(font1);
      g.drawString(Integer.toString(count), 500, 100);
   }

   public static void main(String[] args) {
      JFrame frame = new JFrame("Basic Game");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      SpaceShip ex;
      try {
         ex = new SpaceShip();
         frame.getContentPane().add(ex);
         frame.pack();
         frame.setResizable(false);
         frame.setVisible(true);
         ex.requestFocus();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}