Question

Hi guys I'm super new to Java; I've looked around and haven't been able to find an answer to this question. Any chance you could help me?

Here is an example of what I'm trying to achieve.

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
}
}}

Now the other class, all imports left out for readability.

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

Now the graphics part

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

Now for the question - I want to use the method paint from the Class Board in the Class FrameWork - But can't get it to work - any ideas ? I'm offering a bazillion units of good karma to anyone who has an idea.

Was it helpful?

Solution

The general way to do most Swing drawing is via passive graphics. This means:

  • Do the drawing itself in the paintComponent(Graphics g) method of a JPanel or JComponent.
  • In your MouseListener change the state of some of the fields of the class. In your mouseClicked method you are setting the state of some local variables, and I recommend that you instead make your x and y fields, not local.
  • Then when the mouse listener is done making changes, call repaint() on the JPanel.
  • Then in the paintComponent method, use those fields that were changed in the mouse listener to do your drawing.
  • Don't forget to call the super's paintComponent method in your paintComponent override.
  • Don't forget to read tutorials on Swing Graphics to get the fine points.

Edit

For example, please have a look at a small graphics program that I created for an answer to another recent question.

The drawing occurs in the main class, SpaceShip, which extends JPanel. I add an anonymous inner MouseAdapter class for my Mouse Listener, and inside of the MouseAdapter, I call a method called moveIt, passing in the MouseEvent object.

   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);
}

All moveIt(MouseEvent evt) does is to change the state of two fields, myX and myY, and then calls repaint() on the current class:

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

And then in the class's paintComponent method, I first call the super's paintComponent to allow it to erase any previous old out of date images, then I paint a background image, background, then I draw a sprite that uses the myX and myY variables to tell it where to draw, then I draw some yellow rectangles at locations that are determined by the JPanel's size:

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);
}

The whole thing looks like this:

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();
      }
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top