Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    Hello everyone,

    I'm creating a game called Mouse Trap and I'm having an issue with a graphic drawn using AWT. Basically, when the mouse collides with the cheese, I want the cheese to disappear, or call (cheese[i].hide()). However, the cheese does not appear. hide() works for all other objects that inherit from PFigure, but the cheese will not. It's created a major issue in my game, and basically the only task left to accomplish.

    I believe my problem lies within Cheese.java, method draw(). For example, if I replace it with an example drawing, this problem goes away!:
       public void draw()
       {
          Graphics g = panel.getGraphics();
          g.setColor(Color.blue);
          g.drawOval(x + width / 4 , y + 1, width / 2, height / 2);
          g.setColor(Color.red);
          g.drawLine( x + width / 2, y + height / 2 + 1, x + width / 2, y + 3 * height / 4 );
          g.setColor(Color.green);
          g.drawLine( x + width / 4, y + 5 * height / 8 + 1, x + 3 * width / 4, y + 5 * height / 8 + 1);
          g.setColor(Color.blue);
          g.drawLine( x + width / 2, y + 3 * height / 4, x + width / 4, y + 7 * height / 8 );
          g.drawLine( x + width / 2, y + 3 * height / 4, x + 3 * width / 4, y + 7 * height / 8 );
       }

    I am open to any questions to explain my problem further if needed. I have three classes below that most likely involve the problem, feel free to ask if you need the others.

    PFigure.java (This class cannot be changed as a requirement to my project)
    import java.awt.*;
     
    public abstract class PFigure implements Comparable
    {
       protected int x, y;           // Current position of the figure
       protected int width, height;  // Drawn (displayed) this size
       protected int priority;       // Can use to determine "winner"
       protected Panel panel;        // Panel the figure lives on
     
       public PFigure ( int startX, int startY, int _width, int _height, 
                        int pr, Panel p )
       {
           x = startX;
           y = startY;
           width = _width;
           height = _height;
           priority = pr;
           panel = p;
       }
     
       // Can use this in "battles", which figures is "greater"
       public int compareTo(Object o)
       {
          if( o instanceof PFigure )
             return priority - ((PFigure)o).priority;
          return Integer.MAX_VALUE;
       }
     
       // Has "this" figure collided with p?
       public boolean collidedWith ( PFigure p )
       {
          if (  p == null )
             return false;
     
          return ( x + width ) >= p.x && ( p.x + p.width ) >= x &&
                 ( y + height ) >= p.y && ( p.y + p.height ) >= y;
       }
     
       // Can be used for moving by keyboard or mouse
       public void move ( int deltaX, int deltaY )
       {
          x = x + deltaX;
          y = y + deltaY;
       }
     
       public void hide()
       {
          Graphics g = panel.getGraphics();
          Color oldColor = g.getColor();
          g.setColor(panel.getBackground());
          g.fillRect(x, y, width, height);
          g.setColor(oldColor);
       }
     
       // Can be automatic move, for example, called based on timer
       public void move()
       {
       }
     
     
       // Draw the figure.
       // Each derived class will write their own drawing method.
       // The first line should be:
       //    Graphics g = panel.getGraphics();
       abstract public void draw();
     
     
    }



    Cheese.java
    import java.awt.*;
     
    public class Cheese extends PFigure
    {
     
       public Cheese(int startX, int startY, Panel p)
       {
          super(startX, startY, 60, 50, 0, p);
       }
     
       @Override
       public void draw()
       {
          Polygon cheese = new Polygon(); //
          cheese.addPoint(x , y);
          cheese.addPoint(x + 60, y);
          cheese.addPoint(x + 20, y - 50);
     
          Graphics g = panel.getGraphics();
          g.setColor(Color.yellow);
          g.fillPolygon(cheese);
          g.setColor(Color.black);
          g.drawPolygon(cheese);
          g.drawOval(x + 17, y - 32, width / 4, height / 4);
          g.drawOval(x + 11, y - 15, width / 5, height / 5);
          g.drawOval(x + 30, y - 15, width / 5, height / 5);
       }
     
    }

    MouseTrapGame.java
    import java.awt.*;
    import java.awt.event.ActionEvent;
     
    public class MouseTrapGame extends java.awt.Frame
                               implements java.awt.event.ActionListener {
     
       private PFigureList listOfFigures = new PFigureList();
       private Mouse mouse;
       private MouseTrap mouseTrap;
       private Broom broom;
       private Cheese[] cheeses = new Cheese[5];
     
       private Dialog winMsg = new Dialog(this);
       private Dialog loseMsg = new Dialog(this);
     
       private int cheeseLeft = 5;
     
       private javax.swing.Timer moveTimer = new javax.swing.Timer(200, this);
     
       /**
        * Creates new form MouseTrapGame
        */
       public MouseTrapGame()
       {     
          initComponents();
          setSize(1000, 800);
          setLocationRelativeTo(null);
          spawnCheese();
          spawnTraps();
          spawnBrooms();
          mouse = new Mouse(gamePanel);      
          gamePanel.requestFocus();
          moveTimer.start();
       }
     
       private void displayWin()
       {
          winMsg.add(new Label("Congratulations! You won!"));
          winMsg.setSize(200, 100);
          winMsg.setLocationRelativeTo(null);
          winMsg.setVisible(true);
       }
     
       private void displayLose()
       {
          loseMsg.add(new Label("You lose..."));
          loseMsg.setSize(150, 100);
          loseMsg.setLocationRelativeTo(null);
          loseMsg.setVisible(true);
       }
     
       @Override
       public void actionPerformed(ActionEvent ae)
       {
          if (listOfFigures.checkCollision(mouse))
          {
             moveTimer.stop();
             displayLose();
          }
          if (cheeseLeft == 0)
          {
             moveTimer.stop();
             displayWin();
          }
          mouse.draw();
          for (int i = 0; i < 5; i++)
             cheeses[i].draw();
          listOfFigures.hideAll();
          listOfFigures.moveAll();
          listOfFigures.drawAll();
          cheeseLeftField.setText(String.valueOf(cheeseLeft));      
       }
     
       private void spawnTraps()
       {
          int startX;
          int startY;
          for (int i = 0; i < 4; i++)
          {
             startX = 200 + (int) (Math.random() * 700);
             startY = 50 + (int) (Math.random() * 650);
             mouseTrap = new MouseTrap(startX, startY, gamePanel);
             listOfFigures.add(mouseTrap);
          }
       }
     
       private void spawnBrooms()
       {
          int startX;
          int startY;
          for (int i = 0; i < 4; i++)
          {
             startX = 200 + (int) (Math.random() * 700);
             startY = 50 + (int) (Math.random() * 650);
             broom = new Broom(startX, startY, gamePanel);
             listOfFigures.add(broom);
          }
       }
     
       private void spawnCheese()
       {
          int startX;
          int startY;
     
          for (int i = 0; i < 5; i++)
          {
             startX = 20 + (int) (Math.random() * 750);
             startY = 20 + (int) (Math.random() * 600);
             cheeses[i] = new Cheese(startX, startY, gamePanel);
             System.out.println(startX);
             System.out.println(startY);
          }
       }
     
       /**
        * This method is called from within the constructor to initialize the
        * form. WARNING: Do NOT modify this code. The content of this method is
        * always regenerated by the Form Editor.
        */
       // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
       private void initComponents() {
     
          gamePanel = new java.awt.Panel();
          cheeseLeftLabel = new java.awt.Label();
          cheeseLeftField = new java.awt.TextField();
     
          setMinimumSize(new java.awt.Dimension(1000, 800));
          setTitle("Mouse Trap Game 243");
          addWindowListener(new java.awt.event.WindowAdapter() {
             public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
             }
          });
          setLayout(null);
     
          gamePanel.setBackground(new java.awt.Color(0, 153, 153));
          gamePanel.addKeyListener(new java.awt.event.KeyAdapter() {
             public void keyPressed(java.awt.event.KeyEvent evt) {
                mouseMover(evt);
             }
          });
          add(gamePanel);
          gamePanel.setBounds(0, 0, 1000, 750);
     
          cheeseLeftLabel.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
          cheeseLeftLabel.setText("Cheese Left:");
          add(cheeseLeftLabel);
          cheeseLeftLabel.setBounds(375, 750, 120, 30);
     
          cheeseLeftField.setName(""); // NOI18N
          add(cheeseLeftField);
          cheeseLeftField.setBounds(510, 760, 70, 20);
     
          pack();
       }// </editor-fold>//GEN-END:initComponents
     
       /**
        * Exit the Application
        */
        private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
           System.exit(0);
        }//GEN-LAST:event_exitForm
     
       private void mouseMover(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mouseMover
          mouse.hide();
          if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN)
             mouse.move(0, 10);
          else if ( evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP )
             mouse.move(0, -10);
          else if ( evt.getKeyCode() == java.awt.event.KeyEvent.VK_LEFT )
             mouse.move(-10, 0);
          else if ( evt.getKeyCode() == java.awt.event.KeyEvent.VK_RIGHT )
             mouse.move(10, 0);
          mouse.draw();
     
          for (int i = 0; i < cheeseLeft; i++)
             if (mouse.collidedWith(cheeses[i]))
             {
                cheeses[i].hide();
                cheeseLeft--;
             }
     
       }//GEN-LAST:event_mouseMover
     
       /**
        * @param args the command line arguments
        */
       public static void main(String args[]) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                new MouseTrapGame().setVisible(true);
             }
          });
       }
       // Variables declaration - do not modify//GEN-BEGIN:variables
       private java.awt.TextField cheeseLeftField;
       private java.awt.Label cheeseLeftLabel;
       private java.awt.Panel gamePanel;
       // End of variables declaration//GEN-END:variables
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,440
    Thanks
    49
    Thanked 2,217 Times in 2,190 Posts

    Default Re: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    The posted code won't compile for testing because of missing class definitions.

    Can you make a small, complete program that compiles, executes and shows the problem?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2014
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    I'm not sure on how I could slim down my program to just show the problem.

    Here is a link to download the program folder (this way the images used in the game are also included) if that helps...

    Download Prog5.zip @ UppIT

    If you can get this to run, the problem is when the mouse touches the cheese. Even though my key event tells the cheese to hide(), the cheese is not erased and drawn at another location. This only happens with user graphically-drawn images. The images that are loaded from file all work fine.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,440
    Thanks
    49
    Thanked 2,217 Times in 2,190 Posts

    Default Re: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    If you can't make a small, complete program that compiles and shows the problem then I guess you can wait until someone comes that is willing to do what you are asking.
    Good luck.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,661
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    Are you redrawing everything at once or just individual PFigure objects at a time?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,302
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: [Java AWT (No Swing)] - Problem with hiding user-drawn graphics

    Quote Originally Posted by Chassy13 View Post
    I'm not sure on how I could slim down my program to just show the problem.
    Suggested reading: Short, Self Contained, Correct Example

    Graphics g = panel.getGraphics();

    You should not be calling getGraphics on a Component in this manner. Learn how to perform custom painting, which applies to AWT and Swing
    Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing)

Similar Threads

  1. OpenGL with Swing/AWT/ whatever Java gui
    By Lablabla in forum AWT / Java Swing
    Replies: 1
    Last Post: May 4th, 2012, 09:15 AM
  2. JAVA AWT GRAPHICS REMOVE SOMETHING THAT IS DRAWN
    By michael55131 in forum AWT / Java Swing
    Replies: 2
    Last Post: April 18th, 2012, 08:08 AM
  3. Issues with selecting a drawn circle on graphics
    By Diplo in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 31st, 2011, 11:53 AM
  4. IE browser in Java swing/AWT Frame
    By gafaec in forum Java Native Interface
    Replies: 0
    Last Post: April 9th, 2011, 05:16 AM
  5. simple game with swing and awt problem
    By Pulse_Irl in forum AWT / Java Swing
    Replies: 2
    Last Post: October 12th, 2010, 02:04 PM