1

I've been having some problems with this code, the graphics seem to not want to update for some odd reason. I have no clue how to fix this and it has really been annoying trying to fix this please help! Here is the code:

package org.jeopredy;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.*;

public class Main extends JFrame {

public Main() {
    super("Jeopredy");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(517, 640);
    this.setVisible(true);
    this.add(new panel());
    this.addMouseListener(new panel());
}

public static void main(String args[]) {
    new Main();
}

private class panel extends JPanel implements MouseListener {

    public Rectangle[][] tiles = new Rectangle[5][6];

    public boolean start, question, answer;

    public String[][] Catagories = { { "House of", "representitives" },
            { "Senate" }, { "President" }, { "Vice president" },
            { "Supreme court" } };

    public String[][] Questions = { { "1", "2", "3", "4", "5" },
            { "1", "2", "3", "4", "5" }, { "1", "2", "3", "4", "5" },
            { "1", "2", "3", "4", "5" }, { "1", "2", "3", "4", "5" } };

    public String[][] Answers = { { "", "", "", "", "" },
            { "", "", "", "", "" }, { "", "", "", "", "" },
            { "", "", "", "", "" }, { "", "", "", "", "" } };

    public Point q, a;

    public ArrayList<Point> used = new ArrayList<Point>();

    public panel() {
        start = true;
        for (int x = 0; x < 500; x += 100) {
            for (int y = 0; y < 600; y += 100) {
                tiles[x / 100][y / 100] = new Rectangle(x, y, 100, 100);
            }
        }
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        // super.paintComponent(g);
             //g.setColor(Color.white);

         System.out.println("Start: " + start + " question: " + question
         + " answer: " + answer);
        if (start) {
            int i = 0;
            for (String[] str : Catagories) {
                if (str.length == 1) {
                    g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
                } else {
                    g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
                    g.drawString(str[1], tiles[i][0].x, tiles[i][0].y + 30);
                }
                i++;
            }
            for (Rectangle[] rect : tiles) {
                for (Rectangle r : rect) {
                    g.drawRect(r.x, r.y, r.width, r.height);
                }
            }
        } else if (question) {
            // System.out.println("QUeStionJOSNLN");
            g.drawString(Questions[q.x][q.y], 100, 100);
        }
        repaint();
    }

    @Override
    public void mouseClicked(MouseEvent arg0) {
        Point p = new Point(arg0.getPoint().x - 17, arg0.getPoint().y - 40);
        // repaint();
        if (start) {
            for (int x = 0; x < tiles.length; x++) {
                for (int y = 0; y < tiles[x].length; y++) {
                    if (tiles[x][y].contains(p) && y != 0) {
                        question = true;
                        start = false;
                        answer = false;
                        q = new Point(x, y - 1);
                        used.add(q);
                    }
                }
            }
        } else if (question) {
            answer = true;
            question = false;
            start = false;
        } else if (answer) {
            start = true;
            answer = false;
            question = false;
        }

    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
}
}
Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
user1826677
  • 29
  • 1
  • 2

2 Answers2

3
  1. First of all, you are never ever supposed to override paint(). I think it is main reason of your issues.

Difference between paint, paintComponent and paintComponents in Swing

  1. Use SwingUtilities.invokeLater() to load GUI

  2. Don't extend JFrame, it is not recommended at all, and useless in the code above

  3. private class panel extends JPanel implements class should start with capital letter like MyPanel

Community
  • 1
  • 1
Nikolay Kuznetsov
  • 8,896
  • 9
  • 49
  • 94
  • 2
    While all those advices are correct they are not the source of his problems. His problems comes from 1) instantiating multiple times the `panel`, 2) calling `repaint()` in `paint()` (that's a real killer) 3) `JFrame.setVisible(true)` not being the last line called to init the UI 4) Not calling either `pack()` nor `validate()` nor `revalidate()` – Guillaume Polet Jan 16 '13 at 09:58
3

While I dig around, lets start with...

public void paint(Graphics g) { // <<-- This is bad
    // super.paintComponent(g);
    //g.setColor(Color.white);

    System.out.println("Start: " + start + " question: " + question+ " answer: " + answer);
    if (start) {
        int i = 0;
        for (String[] str : Catagories) {
            if (str.length == 1) {
                g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
            } else {
                g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
                g.drawString(str[1], tiles[i][0].x, tiles[i][0].y + 30);
            }
            i++;
        }
        for (Rectangle[] rect : tiles) {
            for (Rectangle r : rect) {
                g.drawRect(r.x, r.y, r.width, r.height);
            }
        }
    } else if (question) {
        // System.out.println("QUeStionJOSNLN");
        g.drawString(Questions[q.x][q.y], 100, 100);
    }
    repaint(); // <<-- This is bad
}

You should avoid overriding paint. There are plenty of reasons, but basically, now you've completely destroyed the entire paint chain. Painting in Swing is complex and VERY easy to ruin. You MUST call super.paint(g).

Better to override paintComponent, don't forget to call super.paintComponent!!

NEVER change the UI from within ANY paint method. Paint is normally being called in response to a repaint request, modifying the UI in any that might cause another request will send you down a slippery slope of CPU overload and resource hogging...

Updated

this.add(new panel());
this.addMouseListener(new panel());

This is never going to send the mouse events to the panel that is on the screen. You need to register the mouse listener against the panel that is on the screen.

You'd actually be better doing this...

public panel() {
    addMouseListener(this);
    //...continue...
}

Update #2

Try and remember, paints are stateless. What was previously painted will not be present on the next paint cycle. What ever you need painted, must be painted on each cycle.

Update #3

I'm a little stumped as to exactly what you program is trying to achieve, but have a look at the alterations and see if that helps...

public class Main extends JFrame {

  public Main() {
    super("Jeopredy");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(517, 640);
    this.add(new panel());
    this.setVisible(true);
  }

  public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        new Main();
      }
    });
  }

  private class panel extends JPanel implements MouseListener {

    public Rectangle[][] tiles = new Rectangle[5][6];
    public boolean start, question, answer;
    public String[][] Catagories = {{"House of", "representitives"},
      {"Senate"}, {"President"}, {"Vice president"},
      {"Supreme court"}};
    public String[][] Questions = {{"1", "2", "3", "4", "5"},
      {"1", "2", "3", "4", "5"}, {"1", "2", "3", "4", "5"},
      {"1", "2", "3", "4", "5"}, {"1", "2", "3", "4", "5"}};
    public String[][] Answers = {{"", "", "", "", ""},
      {"", "", "", "", ""}, {"", "", "", "", ""},
      {"", "", "", "", ""}, {"", "", "", "", ""}};
    public Point q, a;
    public ArrayList<Point> used = new ArrayList<Point>();

    public panel() {
      addMouseListener(this);
      start = true;
      for (int x = 0; x < 500; x += 100) {
        for (int y = 0; y < 600; y += 100) {
          tiles[x / 100][y / 100] = new Rectangle(x, y, 100, 100);
        }
      }
      repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g); 

      System.out.println("Start: " + start + " question: " + question
          + " answer: " + answer);
      if (start) {
        int i = 0;
        for (String[] str : Catagories) {
          if (str.length == 1) {
            g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
          } else {
            g.drawString(str[0], tiles[i][0].x, tiles[i][0].y + 20);
            g.drawString(str[1], tiles[i][0].x, tiles[i][0].y + 30);
          }
          i++;
        }
        for (Rectangle[] rect : tiles) {
          for (Rectangle r : rect) {
            g.drawRect(r.x, r.y, r.width, r.height);
          }
        }
      } else if (question) {
        // System.out.println("QUeStionJOSNLN");
        g.drawString(Questions[q.x][q.y], 100, 100);
      }
//      repaint();
    }

    @Override
    public void mouseClicked(MouseEvent arg0) {
//      Point p = new Point(arg0.getPoint().x - 17, arg0.getPoint().y - 40);
      Point p = arg0.getPoint();
      // repaint();
      if (start) {
        for (int x = 0; x < tiles.length; x++) {
          for (int y = 0; y < tiles[x].length; y++) {
            if (tiles[x][y].contains(p) && y != 0) {
              question = true;
              start = false;
              answer = false;
              q = new Point(x, y - 1);
              used.add(q);
            }
          }
        }
      } else if (question) {
        answer = true;
        question = false;
        start = false;
      } else if (answer) {
        start = true;
        answer = false;
        question = false;
      }

      repaint();

    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
      // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent arg0) {
      // TODO Auto-generated method stub
    }

    @Override
    public void mousePressed(MouseEvent arg0) {
      // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
      // TODO Auto-generated method stub
    }
  }
}
MadProgrammer
  • 323,026
  • 21
  • 204
  • 329