Painting in JPanel with PaintComponent.

Hi I've got a problem, if i define my JPanel like this then I can't paint in it.
public class kvadrat
JPanel aPanel;
public void Panel()
  aPanel = new JPanel();
  aPanel.setBackground(Color.white);
  aPanel.add(sendButton);
public void Frame()
  Panel();
  JFrame frame = new JFrame("Considerate Music");
  Container iRutan = frame.getContentPane();
  iRutan.setLayout(new BorderLayout());
  iRutan.add(aPanel);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setBounds(300,300,700,400);
  frame.setVisible(true);
public kvadrat()
  Frame();
public static void main(String[] args)
  new kvadrat();
public void paintComponent(Graphics g)
}I can't use the line super.paintComponent(g); in paintComponent because I don't have any extend. I don't want to have any extends on my class so this is why I'm asking, is there a way to paint on my panel(aPanel) in any other way that using extends. You see if I'd like to add more panels I'll have to create a class for each panel and I don't like that.

2 Ways.
#1: An Inner Class
public class kvadrat{
public kvadrat(){
new MyPanel();
//inner class
public class MyPanel extends JPanel{
// methods
}or
#2: Anonymous Inner Classes (very sloppy)
public class kvadrat
JPanel aPanel;
public void Panel()
// right here:
  aPanel = new JPanel(){
       public void paintComponent(Graphics g){
  // code goes here
  aPanel.setBackground(Color.white);
  aPanel.add(sendButton);
public void Frame()
  Panel();
  JFrame frame = new JFrame("Considerate Music");
  Container iRutan = frame.getContentPane();
  iRutan.setLayout(new BorderLayout());
  iRutan.add(aPanel);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setBounds(300,300,700,400);
  frame.setVisible(true);
public kvadrat()
  Frame();
public static void main(String[] args)
  new kvadrat();
// removed: public void paintComponent(Graphics g)
}

Similar Messages

  • Custom painting on jpanel with scrollable

    i have a jpanel with custom painting. because the painting can be wider than the view of the panel i need to implement scrollbars. i have experimented with implementing scrollable and using scrollpanes but i have no result. i need a hint or a tutorial how this can be done

    ok, that was the key. but perhaps you can help me with two other problems:
    because i dont know how large my panel ( or my scroll-area) has to be, i need to expand it on demand. i tried setpreferredsize for that reason, but nothing happens. i think this method is only for initializing but doesnt seem to function properly at a later point.
    next prop:
    when i scroll my custom panting area the jpanel isnt repainted. i have some difficulties finding the right eventlistener so that i can get scrollbar events (repaint after each move)

  • Scrolling a custom Component (e.g. JPanel) with overridden paint(Graphic g)

    Hi.
    I’m creating an application for modelling advanced electrical systems in a house. Until now I have focused on the custom canvas using Java2D to draw my model. I can move the model components around, draw lines between them, and so on.
    But now I want to implement a JScrollPane to be able to scroll a large model. I’m currently using a custom JPanel with a complete override of the paint(Graphic g) method.
    Screen-shot of what I want to scroll:
    http://pchome.grm.hia.no/~aalbre99/ScreenShot.png
    Just adding my custom JPanel to a JScrollPane will obviously not work, since the paint(Graphic g) method for the JPanel would not be used any more, since the JScrollPane now has to analyze which components inside the container (JPanel) to paint.
    So my question is therefore: How do you scroll a custom Component (e.g. JPanel) where the paint(Graphic g) method is totally overridden.
    I believe the I have to paint on a JViewport instructing the JScrollPane my self, but how? Or is there another solution to the problem?
    Thanks in advance for any suggestions.
    Aleksander.

    I�m currently using a custom JPanel with a complete override of the paint(Graphic g) method. Althought this isn't your problem, you should be overriding the paintComponent(..) method, not the paint(..) method.
    But now I want to implement a JScrollPane to be able to scroll a large model.When you create a custom component to do custom painting then you are responsible for determining the preferredSize of the component. So, you need to override the getPreferredSize(...) method to return the preferredSize of your component. Then scrolling will happen automatically when the component is added to a scrollPane.

  • Problem with paintComponent, and CPU usage

    Hi,
    I had the weirdest problem when one of my JDialogs would open. Inside the JDialog, I have a JPanel, with this paintComponent method:
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Color old = g.getColor();
    g.setColor(Color.BLACK);
    g.drawString("TEXT", 150, 15);
    g.setColor(old);
    parent.repaint();
    now when this method is called, the CPU usage would be at about 99%. If i took out the line:
    parent.repaint();
    the CPU usage would drop to normal. parent is just a reference to the Jdialog that this panel lies in.
    Anyone have any ideas on why this occurs?
    Thanks!

    1) I never got a stack overflow, and i have had this in my code for quite sometime...If you called paint() or paintComponent(), I'm betting that you would see a stack overflow. The way I understand it, since you are calling repaint(), all you are doing is notifying the repaint manager that the component needs to be repainted at the next available time, not calling a paint method directly. good article on how painting is done : http://java.sun.com/products/jfc/tsc/articles/painting/index.html#mgr
    2) If this is the case, and the two keep asking eachother to paint over and over, .....
    see above answer

  • Setting the bounds of a JPanel with double values

    Hi,
    I want to use a JPanel in my application, but the setBounds() method is limited to only int. Now I'm wondering if there is a way to set the bounds on the JPanel with doubles, so I can paint it for example x = 15.5;
    I was thinking about override the setBounds method, but is this even possible without causing problems to other methods? Or is there an easier way?
    Grtz

    Encephalopathic wrote:
    What is the purpose of this? Why are you using setBounds to begin with rather than layout managers?The reason I'm using absolute positioning is because the JPanels can be dragged to wherever they want. I can live with the fact that it isn't possible and solve it in another way, but I was just wondering if it is possible.

  • How to add a JPanel with label and border line

    hi,
    I want a Jpanel with label and border line like this.Inside it i need to have components.Is there a resuable component to bring this directly??
    Any solution in this regards.???
    Label-----------------------------------------------------------
    | |
    | |
    | |
    | |
    | |
    |________________________________________ |

    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html]How to Use Borders

  • JPanel with Image just doesn't want to show

    Hello,
    i am trying to create a JPanel with a JLabel to which i assign an ImageIcon, but for some reason the JPanel seems not to appear in my JFrame.
    Here's the code: private void jbInit() throws Exception
        NumberListener numListener = new NumberListener();
        frame = new JFrame();
        frame.setTitle("Error Manager");
        frame.setLayout(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;
        numberList = new JList(numbers);
        numberList.addListSelectionListener(numListener);
        numberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane listScroller = new JScrollPane(numberList);
        listScroller.setPreferredSize(new Dimension(250, 80));
        frame.getContentPane().add(listScroller, gbc);
        imgPanel = new JPanel();
        imgPanel.setSize(300, 250);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image img = toolkit.createImage("Somepic.png");
        imgPanel.add(new JLabel(new ImageIcon(img)));
        gbc.gridx = 1;
        gbc.gridy = 0;
        frame.getContentPane().add(imgPanel, gbc);
        frame.pack();
        frame.setVisible(true);
      }

    Sorry forgot to close the code tags...
    private void jbInit() throws Exception
        NumberListener numListener = new NumberListener();
        frame = new JFrame();
        frame.setTitle("Error Manager");
        frame.setLayout(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;
        numberList = new JList(numbers);
        numberList.addListSelectionListener(numListener);
        numberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane listScroller = new JScrollPane(numberList);
        listScroller.setPreferredSize(new Dimension(250, 80));
        frame.getContentPane().add(listScroller, gbc);
        imgPanel = new JPanel();
        imgPanel.setSize(300, 250);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image img = toolkit.createImage("1_Alpinweiss_III.png");
        imgPanel.add(new JLabel(new ImageIcon(img)));
        gbc.gridx = 1;
        gbc.gridy = 0;
        frame.getContentPane().add(imgPanel, gbc);
        frame.pack();
        frame.setVisible(true);
      }

  • Popup containing a JPanel with a JComboBox

    I like to get a Popup containing a JPanel with a JComboBox and some other stuff.
    There are two difficulties:
    - it is not possible to use a Combobox with a light weight popup. So I set combobox.LightWeightPopupEnabled(false). Otherwise the combobox popup won't be shown.
    - If the user changes the popups size (see code: this.getSize() returns a different dimension because of a new Frame size). The combobox popups won't be shown proper after a while.
    Does someone know, why it is not possible to use comboboxes with light weight popups?
    Does somebody know, how to fix the size problem?
    I am using JDK 1.4.1 for Windows Systems.
      private Popup getPopup(){
        if (popup != null) {
          hidePopup();
        Point p = this.getLocationOnScreen();
        Dimension inputSize = this.getSize();
        Dimension tableSize = tablePopup.getSize();
        if( ( p.y + tableSize.height ) < screenSize.height) {
          // will fit below input panel
          popup = factory.getPopup( this, tablePopup,
                                    p.x, p.y + (int)inputSize.height );
        } else {
          // need to fit it above input panel
          popup = factory.getPopup( this, tablePopup,
                                    p.x, p.y - (int)tableSize.height );
        return popup;

    Ok, it works proper with Windows L&F. So I replaced
    private PopupFactory factory =  PopupFactory.getSharedInstance();by
    private WindowsPopupFactory factory = new WindowsPopupFactory();

  • Report Painter: Change descriptions with *

    Hi
    I have a doubt: In the Report Painter >> the fields with *   Color Blue. Is possible to change the description or is Standard ??
    Merry christmas

    Please search for available information before posting, do not post basic questions.
    Thread locked.
    Thomas

  • How to print out a JPanel with its components

    Hello,
    I want to print out a JPanel where several components are placed in. The problem is just that neither the printAll() method nor the print() method works to do so. There's always just a print of the empty JPanel. Is there in general a possibility to print out a JPanel with its components or are I'm on the wrong way ?
    Thanx,
    Findus

    I just posted this link and it works here:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=361445&tstart=0&trange=15

  • Painting in JPanels

    Hey guys, thanks for the help with the last question. Heres another for the same program!
    So this program generates a JFrame which is populated with JPanel's in a gridLayout() format. The grid is supposed to represent a maze which is navigated by clicking on the appropriate panels.
    The first problem I'm having is trying to get the starting square, the current square and the squares that have previously stepped on to change color. Also the current square should show a circle to indicate where you are.
    Instead of doing that the squares are just showing random graphics on them due to an arbitrary line of code i put in:
    Graphics g = getGraphics();If i take that out then nothing changes color/graphics.
    The second problem I'm having is when i load a new maze (or the same one) instead of replacing the displayed one it tries to squish them both in. Yet when i print out all the values like the number of columns in the gridLayout it they are all correct. I'm hoping this is just a display error and will be fixed with the first problem.
    The Maze.java class brings everything together and calls the Walls.java class which creates and adds the JPanel's which are GridPanel.java objects. The Move.java and Maze.java alters the GridPanel's to be current or not... Good Luck =) and thanks heaps as always! YOU GUYS ARE LIFESAVERS!!!
    //Ass2.java
    public class Assign2
         public static void main(String[] args)
              Maze theMaze = new Maze();
    //Maze.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Maze extends JFrame
         Vector<String> data = new Vector<String>();
         GridPanel[][] panel;
         private int[] endPoints = new int[4];
         private int[] size = new int[2];
         private int moveNum;
         private int theSize;
         private int cX;
         private int cY;
         private int pX;
         private int pY;
         public Maze()
              MazeApp s = new MazeApp(this);
              moveNum = 0;
              File f = new File("maze.txt");
              readMaze(f);
         public void readMaze(File fName)
              File fileName = fName;
              Read r = new Read();
              data.clear();
              size = r.readFile(endPoints, data, fileName);
              theSize = (size[1] * size[0]);
              cX = endPoints[0];
              cY = endPoints[1];
              GridLayout layout = new GridLayout();
              layout.setRows(size[1]);
              layout.setColumns(size[0]);
              this.setLayout(layout);
              System.out.println(data.size());
              makeMaze();
         public void makeMaze()
              panel = new GridPanel [size[1]][size[0]];
              Walls w = new Walls(data, size, this);
              w.drawWalls(panel);
              panel[endPoints[1]][endPoints[0]].setStart();
              panel[endPoints[3]][endPoints[2]].setEnd();
              this.setSize(size[0]*100, size[1]*100);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setVisible(true);
         public void checkMove(Point clicked, int w, int h, int wall)
              pY = (int)(clicked.getX())/w;
              pX = (int)(clicked.getY())/h;
              Move m = new Move(cX, cY, pX, pY, w, h, wall);
              if(m.check() == 1) //MOVE NORTH
                   if((panel[cX-1][cY].checkWall() != 2) && (panel[cX-1][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 2) //MOVE SOUTH
                   if((panel[cX][cY].checkWall() != 2) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 3) //MOVE WEST
                   if((panel[pX][pY].checkWall() != 1) && (panel[pX][pY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 4) //MOVE EAST
                   if((panel[cX][cY].checkWall() != 1) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 0 )
              {JOptionPane.showMessageDialog(this, "Invalid Move! Invalid square selected!\nPlease choose an adjacent square.");}
         public void setCurrent()
              panel[cX][cY].setUsed();
              panel[pX][pY].setCurrent();
              cX = pX;
              cY = pY;
              moveNum++;
              if(cY == endPoints[2] && cX == endPoints[3])
              {JOptionPane.showMessageDialog(this, "Congratulations!\nYou finished in" + moveNum + "moves!");}
    // MazeApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class MazeApp extends JFrame
           private Maze theMaze;
           public MazeApp(Maze m)
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   theMaze = m;
                   // create the menu bar to hold the menus...
                   JMenuBar menuBar = new JMenuBar();
                   // create the menus to hold the menu items...
                   JMenu menuFile = new JMenu("File");
                   JMenu menuOptions = new JMenu("Options");
                   JMenu menuHelp = new JMenu("Help");
                   // create file menu options:
                   JMenuItem itemLoad = new JMenuItem("Load");
                   JMenuItem itemSaveAs = new JMenuItem("Save As...");
                   JRadioButtonMenuItem itemModePlay = new JRadioButtonMenuItem("Play");
                   JRadioButtonMenuItem itemModeEdit = new JRadioButtonMenuItem("Edit");
                   JMenuItem itemExit = new JMenuItem("Exit");
                   //create options menu:
                   JRadioButtonMenuItem itemNoRats = new JRadioButtonMenuItem("No Rats");
                   JRadioButtonMenuItem itemOneRat = new JRadioButtonMenuItem("One Rat");
                   JRadioButtonMenuItem itemTwoRats = new JRadioButtonMenuItem("Two Rats");
                   //create help option:
                   JMenuItem itemHelp = new JMenuItem("Help");
                   JMenuItem itemAbout = new JMenuItem("About");
                   //set default options:
                   itemModePlay.setSelected(true);                    
                   itemNoRats.setSelected(true);
                   // add File options:
                   menuFile.add(itemLoad);
                   menuFile.add(itemSaveAs);
                   menuFile.addSeparator();
                   menuFile.add(itemModePlay);
                   menuFile.add(itemModeEdit);
                   menuFile.addSeparator();
                   menuFile.add(itemExit);
                   //add Options:
                   menuOptions.add(itemNoRats);
                   menuOptions.add(itemOneRat);
                   menuOptions.add(itemTwoRats);
                   //add Help options:
                   menuHelp.add(itemHelp);
                   menuHelp.add(itemAbout);
                   // add the menu to the menu bar...
                   menuBar.add(menuFile);
                   menuBar.add(menuOptions);
                   menuBar.add(menuHelp);
                   // finally add the menu bar to the app...
                   m.setJMenuBar(menuBar);
                   //listeners
                   itemExit.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           System.exit( 0 );
                itemLoad.addActionListener(
                   new ActionListener()
                        public void actionPerformed( ActionEvent event )
                             final JFileChooser fc = new JFileChooser();
                             int returnVal = fc.showOpenDialog(MazeApp.this);
                          File fileName = fc.getSelectedFile();
                             if(fileName.exists())
                                  theMaze.readMaze(fileName);
                             else
                                  System.out.println("404. File not found");
                   itemAbout.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           //do stuff
                                           JOptionPane.showMessageDialog(MazeApp.this, "Author: Pat Purcell\[email protected]", "About", JOptionPane.ERROR_MESSAGE);
    //Read.java
    import java.io.*;
    import java.util.Vector;
    public class Read
         private BufferedReader input;
         private String line;
         private String fileName;
         private String[] temp;
         private int[] size = new int[2];
         public int[] readFile(int[] endPoints, Vector<String> data, File fileName)
              try
                   data.clear();
                   FileReader fr = new FileReader(fileName);
                   input = new BufferedReader(fr);
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<2;i++)
                   {size[i] = Integer.parseInt(temp);}
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<4;i++)
                   {endPoints[i] = Integer.parseInt(temp[i]);}
                   line = input.readLine();
                   while (line != null)
                        String[] temp = line.split("\\s");
                        for(int i=0;i<size[0];i++)
                             data.addElement(temp[i]);
                        line = input.readLine();
                   input.close();
              catch (IOException e)
                   System.err.println(e);
              return size;
    }//Walls.java
    import java.util.Vector;
    import java.awt.GridLayout;
    import javax.swing.*;
    public class Walls extends JFrame
         private Vector<String> data = new Vector<String>();
         private int size;
         private Maze bm;
         private int row;
         private int column;
         public Walls(Vector<String> theData, int[] theSize, Maze m)
              data = theData;
              row = theSize[1];
              column = theSize[0];
              size = row*column;
              bm = m;
         public boolean testEast(int position)
              boolean exists;
              String temp = data.get(position);
              int eastData = ((int)temp.charAt(0) - (int)'0');
              if(1 == (eastData))
                   return true;
              return false;
         public boolean testSouth(int position)
              boolean exists;
              String temp = data.get(position);
              int southData = ((int)temp.charAt(1) - (int)'0');
              if(1 == (southData))
                   return true;
              return false;
         public boolean testBoth(int position)
              boolean exists;
              if((testEast(position) && testSouth(position)) == true)
                   return true;
              return false;
         public void drawWalls(GridPanel panel[][])
              int i = 0;
              for(int y=0;y<row;y++)
                   for(int x=0;x<column;x++, i++)
                   if (testBoth(i) == true)
                   {     GridPanel temp = new GridPanel(3, bm);
                        panel[y][x] = temp;
                                  bm.add(temp);}
                   else{
                        if (testEast(i) == true)
                        {     GridPanel temp = new GridPanel(1, bm);
                             panel[y][x] = temp;
                                  bm.add(temp);}
                        else{
                             if (testSouth(i) == true)
                             {     GridPanel temp = new GridPanel(2, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
                             else{
                                  GridPanel temp = new GridPanel(0, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
    }//GridPanel.java
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class GridPanel extends JPanel implements MouseListener
    private int wall;
    private Maze bm;
    private Ellipse2D.Double circle = new Ellipse2D.Double();
    private Graphics gr;
    boolean current = false;
    boolean start = false;
    boolean finish = false;
    public GridPanel(int theWall, Maze m)
         wall = theWall;
         this.addMouseListener(this);
         bm = m;
         public void paintComponent(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(new BasicStroke(1));
              g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              g2.setStroke(new BasicStroke(4));
              if(wall == 0) //NO WALL
              if(wall == 1) //EAST WALL
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(wall == 2) //SOUTH WALL
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              if(wall == 3) //BOTH WALLS
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(current == true)
                   setBackground(SystemColor.green);
                   circle = new Ellipse2D.Double();
                   circle.x = 0;
                   circle.y = 0;
                   circle.height = this.getHeight()-1; // -1 so it fits inside the panel.
                   circle.width = this.getWidth()-1;
                   g2.draw(circle);
                   repaint();
              if(start == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("S", this.getWidth()/2, this.getHeight()/2);}
              if(finish == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("F", this.getWidth()/2, this.getHeight()/2);}
         public int checkWall()
              return wall;
         public void setCurrent()
              Graphics g = getGraphics();
              repaint();
         public void setUsed()
              current = false;
              repaint();
         public void setStart()
              start = true;
              repaint();
         public void setEnd()
              finish = true;
              repaint();
         public void mouseClicked(MouseEvent e){bm.checkMove(this.getLocation(), this.getWidth(), this.getHeight(), wall);}
         public void mouseReleased (MouseEvent e) {}
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
    }//Move.java
    import java.awt.*;
    public class Move
         private int pX;
         private int pY;
         private int cX;
         private int cY;
         private int w;
         private int h;
         private int wall;
         public Move(int x1, int y1, int x2, int y2, int theWidth, int theHeight, int wallCheck)
              pX = x2;
              pY = y2;
              cX = x1;
              cY = y1;
              w = theWidth;
              h = theHeight;
         public int check()
              //System.out.println(cX + " " + (pX + 1));
              if((cX == (pX + 1)) && (cY == pY)) //MOVE NORTH
              {return 1;}
              //System.out.println(cX + " " + (pX - 1));
              if((cX == (pX - 1)) && (cY == pY)) //MOVE SOUTH
              {return 2;}
              //System.out.println(cY + " " + (pY + 1));
              if((cY == (pY + 1)) && (cX == pX))//MOVE WEST
              {return 3;}
              //System.out.println(cY + " " + (pY - 1));
              if((cY == (pY - 1)) && (cX == pX))//MOVE EAST
              {return 4;}
              return 0;
    }This is the file the maze is read out of: Maze.txt6 5
    0 0 3 2
    10 00 01 01 01 10
    10 10 00 01 10 10
    10 10 01 11 10 10
    10 01 01 01 11 10
    01 01 01 01 01 11                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    -> Second proplem that still remains is the circle stays after you leave the square...
    Thats why I suggested you use a Border and not do custom painting. There is no such method as remove(...). You need to repaint the entire panel. If you use a Border you just use setBorder(...) to whatever. So you have two different Borders. One for when the component has focus and one for when the component doesn't.
    -> but the same two problems remain.
    Well, I don't know whats wrong and I am not about to debug your program since I have no idea what it is doing. So create a SSCCE to post.
    see http://homepage1.nifty.com/algafield/sscce.html,
    Basically all you need to do is create a JFrame. Create a "main" panel with a flow layout and add it to the content pane. Then create 3 or 4 panels with a default Border on a black line and add the panels to the "main" panel. Then add you MouseListeners and FocusListeners to the panels. The whole program should be 30 lines of code or so. Understand how that program works and then apply the same concepts to you real program.
    The point is when you attempt to do something new that you don't understand write a simple program so you can prove to yourself that it works. If you can't get it working then you have a simple SSCCE to post and then maybe someone will look at it.

  • Can anyone help with PaintComponent???

    Can someone give me a bit of backgroubd on the paintComponent method in a JPanel?
    I am under the impression that it is called by paint(), and that paint is only called when the screen needs to be refresed.
    However, in my program, paintComponenet is calling over and over continiuously.
    I forced a nullPointerException in order to get a stack trace, and none of my classes are lised in it (except for the one with the paintComponent method).
    Under what circumstaces would the panel constantly call this method?

    This section on "Painting" from the Swing tutorial might help:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to continue with the "Working With Graphics" link at the bottom.

  • Painting on JPanel problem

    i am new in java and im practicing on GUI...
    i wrote this stupid GUI that draw shapes on a JPanel, when i minimize the window and maximize again shapes disapear, i have been told to use the paintComponent( ) instead of getGraphics( ) but i didnt know how since my program is made out of two class...
    i will provide the code so please help a newbie
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.awt.image.RasterFormatException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class can extends JFrame {
        private JPanel pic = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private JPanel p = new JPanel();
        public can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());
            pic.setBackground(Color.white);
            pic.addMouseListener(new locationListener());
            this.add(pic, BorderLayout.CENTER);
            this.add(b1, BorderLayout.WEST);
            this.add(b2, BorderLayout.EAST);
            this.add(b3, BorderLayout.SOUTH);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());
            r = new JRadioButton("rectangle");
            c = new JRadioButton("circle");
            s = new JRadioButton("square");
            ButtonGroup bg = new ButtonGroup();
            bg.add(r);
            bg.add(c);
            bg.add(s);
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            this.add(p, BorderLayout.NORTH);
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private class locationListener implements MouseListener {
            public void mouseClicked(MouseEvent e) {
                shapes shape = new shapes();
                Graphics g = pic.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g, e.getX() - 25, e.getY() - 25);
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private void quit() {
            System.exit(0);
        private void clear() {
            pic.repaint();
        private void saveFile() {
            int count = 1;
            String fileName = "picture.jpeg";
            File file = new File(fileName);
            if (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture"+count+".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
            pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
            } catch (IOException ioe) {
            catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            can c = new can();
            c.setVisible(true);
    }this was the first class and this is the second class that define the shapes
    import java.awt.*;
    public class shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }i dunno how and where to implement the paintComponent( ) in this situation , please help me... and im also having another problemin the saveFile( ) method in the can class, it doesnt increment the naming of the file if it already exists...
    please help me...

    Hey, there were a few design issues in your code so I hope you dont mind me re-coding a few section of it to bring out the usage of the paintComponent(Graphics g) method.
    Also, the save was not working correctly because of the localization of the variables count and filename. I moved them and them global it to work. Also you had to re-create the file instance in order for it to be saved correctly with the new name.
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    public class Can extends JFrame {
        private JPanel p = new JPanel();
        private JButton b1 = new JButton("Clear");
        private JButton b2 = new JButton("Quit");
        private JButton b3 = new JButton("Save");
        private JRadioButton r, c, s;
        private PicturePanel pic = new PicturePanel();  
        private boolean shdClear = false;
        public Can() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800, 600);
            setTitle("Shape Drawer");
            setLayout(new BorderLayout());          
            JPanel buttonPanel = new JPanel();
                buttonPanel.add(b1);
                buttonPanel.add(b2);
                buttonPanel.add(b3);
            b1.addActionListener(new clearListener());
            b2.addActionListener(new quitListener());
            b3.addActionListener(new saveListener());      
            r = new JRadioButton("rectangle");       
            c = new JRadioButton("circle");
            s = new JRadioButton("square");       
            r.setSelected(true);
            p.add(r);
            p.add(c);
            p.add(s);
            ButtonGroup bg = new ButtonGroup();
                bg.add(r);
                bg.add(c);
                bg.add(s);
            getContentPane().add(pic, BorderLayout.CENTER);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH );
            getContentPane().add(p, BorderLayout.NORTH);
        public class PicturePanel extends JPanel implements MouseListener {
            Shapes shape = new Shapes();
            MouseEvent e = null;
            BufferedImage backgroundImage = null;
            public PicturePanel() {
                super();
                setBackground(Color.white);
                addMouseListener(this);
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if(e == null) {
                    return;
                if(shdClear) {
                    backgroundImage.getGraphics().dispose();
                    backgroundImage = null;
                if(backgroundImage == null) {
                    backgroundImage = new BufferedImage( getWidth(), getHeight(),
                        BufferedImage.TYPE_INT_RGB );
                    Graphics g2 = backgroundImage.getGraphics();
                        g2.setColor( getBackground() );
                        g2.fillRect(0,0, getWidth(), getHeight());
                    // added here for performance reasons
                    // could have been added above in the if(shdClear) section 
                    if(shdClear) {
                        shdClear = false;
                        return;
                Graphics g2 = backgroundImage.getGraphics();
                if (r.isSelected()) {
                    shape.rect(g2, e.getX() - 30, e.getY() - 20);
                if (c.isSelected()) {
                    shape.circles(g2, e.getX() - 25, e.getY() - 25);
                if (s.isSelected()) {
                    shape.squares(g2, e.getX() - 25, e.getY() - 25);
                if(backgroundImage != null) {
                    g.drawImage(backgroundImage, 0, 0, this);
            public void mouseClicked(MouseEvent e) {
                this.e = e;
                pic.repaint();
             * Invoked when a mouse button has been pressed on a component.
            public void mousePressed(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when a mouse button has been released on a component.
            public void mouseReleased(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse enters a component.
            public void mouseEntered(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
             * Invoked when the mouse exits a component.
            public void mouseExited(MouseEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
        private class saveListener implements ActionListener {
             * Invoked when an action occurs.
            public void actionPerformed(ActionEvent e) {
                saveFile();
        private class clearListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {           
                clear();
        private class quitListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                quit();
        private void quit() {
            System.exit(0);
        private void clear() {
            shdClear = true;
            pic.repaint();
        int count = 1; // moved so as not be recreated each time
        String fileName = "picture.jpeg";
        private void saveFile() {
            File file = new File(fileName);
            while (file.exists()) {
                System.out.println("hello motto");
                fileName = "picture" + count + ".jpeg";
                System.out.println(fileName);
                count++;
                System.out.println(count);
                file = new File(fileName); // recreate the file
            //pic = (JPanel) getContentPane();
            int w = pic.getWidth();
            int h = pic.getHeight();
            BufferedImage image = (BufferedImage) pic.createImage(w, h);
            Graphics g = image.getGraphics();
            if (g.getClipBounds() != null) {
                g.setClip(0, 0, w, h);
            pic.paint(g);
            try {
                FileOutputStream out = new FileOutputStream(file);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                encoder.encode(image);
                out.flush();
                out.close();
                JOptionPane.showMessageDialog(null, fileName + " Saved", "File Saved",
                JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException ioe) {
            } catch (RasterFormatException rfe) {
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                System.out.println("ERROR: " + e);
            Can c = new Can();
            c.setVisible(true);
    class Shapes {
        public void squares(Graphics g, int x, int y) {
            g.setColor(Color.BLUE);
            g.fillRect(x, y, 50, 50);
        public void rect(Graphics g, int x, int y) {
            g.setColor(Color.RED);
            g.fillRect(x, y, 60, 40);
        public void circles(Graphics g, int x, int y) {
            g.setColor(Color.GREEN);
            g.fillOval(x, y, 50, 50);
    }ICE

  • Painting in JPanel directly

    Hi.
    Can any one help me with how to paint directly in JPanel, I need to paint directly in a swing component, but i dont know in which and how
    How i use the paintComponent method of JPanel class..
    Thanks.

    There are two ways to do this. If you are extending the JPanel class call the paintComponent method and put all your painting in there.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class ThingMie extends JPanel
    // private variables
    public ThingMie()
    // other gui stuff
    setBackground(Color.white);
    setBorder(BorderFactory.createRaisedBevelBorder());
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    // write a string
    g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
    g.setColor(Color.red);
    g.drawString("hello", 6, 10);
    // draw a rectangle
    g.setColor(Color.green);
    g.drawRect(15, 15, 30, 60);
    // draw an ellipse
    g.setColor(Color.blue);
    g.drawOval(150, 20, 50, 100);
    public static void main(String [] args)
    JFrame thing = new JFrame();
    thing.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    thing.getContentPane().add(new ThingMie(), BorderLayout.CENTER);
    thing.setTitle("Painting to a panel");
    thing.setSize(400, 300);
    thing.setVisible(true);
    If you're creating a JPanel within another component, say a JFrame or a JDialog you can use code like this:
    import java.awt.*;
    import javax.swing.*;
    class ThingMie extends JFrame
    // private variables
    private JPanel panel;
         public ThingMie()
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              // other gui stuff
              panel = new JPanel()
                   protected void paintComponent(Graphics g)
                        super.paintComponent(g);
                        // write a string
                        g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
                        g.setColor(Color.red);
                        g.drawString("hello", 6, 10);
                        // draw a rectangle
                        g.setColor(Color.green);
                   g.drawRect(15, 15, 30, 60);
                        // draw an ellipse
                        g.setColor(Color.blue);
                        g.drawOval(150, 20, 50, 100);
              panel.setBackground(Color.white);
              panel.setBorder(BorderFactory.createRaisedBevelBorder());
              getContentPane().add(panel, BorderLayout.CENTER);
         public static void main(String [] args)
              ThingMie thing = new ThingMie();
              thing.setTitle("Painting to a panel");
              thing.setSize(400, 300);
              thing.setVisible(true);
    /***********/

  • Unable to paint (using paint() in JPanel) inside mouse listeners

    This is hard to explain but I'll do my best :)
    I've created a little game and at some point I needed to make images "move" on the JPanel (through paint()), on a checkers-based game board.
    The game works like so:
    it has a mouse listener for clicks and movement, and the main game process is THINK(), REPAINT(), which is repeated until the user wins (the above is inside a while).
    The mouse actions were added to the constructor so they are always active, THINK changes the enemy's locations, and REPAINT simply calls "paint()" again.
    The picture is either an enemy or the player, and it can only "rest" on squares.
    (e.g. point's x and y must be divided in 50).
    While doing that, I wanted to make the movement more sleek and clean,
    instead of them simply jumping from one square to the other with a blink of the eye.
    So, I've created MOVEACTOR, that "moves" an enemy or a player from its current point (actor.getPoint()) to the requested future square (futurePoint).
    //actor = enemy or player, has getPoint() that returnes the current point on the board where he rests on.
    //futurePoint = the new point where the enemy or player should be after the animation.
    //please ignore obvious stuff that has nothing to do with what I asked -- those will be deleted in the future, for they are only temporary checking extra lines and stuff.
    //also feel free to ignore the "jumpX" things. Those are just to change images, to imitate physical "jumping" animation.
    protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");
         }I use the above on several occasions:
    [1] When an enemy moves. Summary:
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             moveActor(actors[currentVillain], futurePoint);[2] When the player moves. Summary (this is inside the mouseClicked listener):
    //mouseLocation = MouseWEvent.getPoint();
    //stl, str, etc = rectangles that represents future location of the player on the board.
              if (waitingForPlayer) {
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
    SO ... WHAT IS THE QUESTION?!?
    What I see when I run the game:
    the animation of the enemy (first code) works, but the animation of the player (second code, inside the mouse listeners) -- doesn't!
    The purpose of the moveActor is to move the enemy or player pixel by pixel, until its in the future point,
    instead of skipping the pixels between the squares and going straight for the future location.
    So what comes out is, that the enemy is moving pixel by pixel, and the player simply jumps there!
    I doublechecked and if I use moveActor with the player OUTSIDE the mouse listener, it works (i think).
    Any ideas what is the source of this problem?
    Hope I made myself clear enough :D
    Thanks,
    Eshed.

    I don't know if thats what happens, nor how to fix the thread problems. The mosue actions are "threaded" by default, no? And the moving thing happens after the mouse was clicked, and if the enemy's moving the user can still move his mouse and get responses, like "enemy didn't move yet" and stuff.
    Here's the complete GamePanel.java:
    //drawings
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    //events
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    //tools
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.MediaTracker;
    import java.awt.Dimension;
    //panels, buttons, etc
    import javax.swing.JPanel;
    /** The Game Panel.
    *The panel's size is 500x500, and each square is squaresized 50.
    *This is where the game actually "exists". Here its being updated, drawn, etc.*/
    public class GamePanel extends JPanel implements Runnable
         private static final int PWIDTH = 500;                              //Width of the panel.
         private static final int PHEIGHT = 500;                              //Height of the panel.
         private static final int SQUARESIZE = 50;                         //Size of each square in the panel.
         private boolean working = false;                                   //Game keeps going until this is FALSE.
         private volatile Thread animator;                                   //The animation thread.
         private ImageIcon stand,fall;                                        //Images for the background - ground and water.
         private static ImageHandler ih;                                        //An image handler for image loading.
         private int numOfImages = 0;                                        //Number of total images (max image qunatity).
         private Actor[] actors;                                                  //The actors: [0] is the player, rest are enemies.
         private Point mouseLocation;                                        //Saves the current mouse location for checking where the mouse is
         protected Rectangle stl, str, sbl, sbr;                              //squares around the player, for mouse stuff.
         protected Rectangle v1, v2, v3, v4, v5;                              //squares around each villain, for mouse stuff.
         protected Rectangle wholeBoard = new Rectangle(0,0,PWIDTH,PHEIGHT);
         protected boolean waitingForPlayer = true;
         private int currentVillain = 1;
         private boolean inSight = false;
         // in methods other than the listeners.
         /** Waits for the Window (or whatever this panel loads in) to settle in before doing anything.*/
         public void addNotify()
              super.addNotify();                                                                           //When the super finishes...
              go();                                                                                                         //..go, go, go!
         /** Starts the game.*/
         private void go()
              if (animator==null || !working)     {                                        //if the game isn't in process,
                   animator = new Thread(this);                                        //make the animator as the main process,
                   animator.start();                                                                      //and start it (because of the runnable it launches "run()".
         /**Constructor of the Game Panel.*/
         public GamePanel()
              numOfImages = 14;                                                                      //Total image num.
              ih = new ImageHandler(this,numOfImages);               //Setting a new image handler for the images.
              ih.addImage("player_idle", "images/p_idle.png");          //Adding images.
              ih.addImage("villain_idle", "images/v_idle.png");
              ih.addImage("stand", "images/stand.gif");
              ih.addImage("fallpng", "images/fall.png");
              ih.addImage("fall", "images/fall.gif");
              ih.addImage("ghost", "images/ghost.gif");
              ih.addImage("villain_angry", "images/v_angry.png");
              ih.addImage("player_angry", "images/p_angry.png");
              ih.addImage("player_jump1", "images/p_j1.gif");
              ih.addImage("player_jump2", "images/p_j2.gif");
              ih.addImage("player_jump3", "images/p_j3.gif");
              ih.addImage("villain_jump1", "images/v_j1.gif");
              ih.addImage("villain_jump2", "images/v_j2.gif");
              ih.addImage("villain_jump3", "images/v_j3.gif");
              setPreferredSize(new Dimension(PWIDTH,PHEIGHT));     //Setting size of the panel.
              setFocusable(true);                                                                                //This and the next makes the window "active" and focused.
              requestFocus();
              /** Mouse hovering settings.*/
              addMouseMotionListener( new MouseMotionAdapter()
                   /** When the mouse is moving, do these stuff.*/
                   public void mouseMoved(MouseEvent e1)
                         *  |  stl  |       | str   |          stl = squareTopLeft
                         *  |_______|_______|_______|       str = squareTopRight
                        *   |       |current|       |         current = player's location
                        *   |_______|_______|_______|       sbl = squareBottomLeft
                        *   |  sbl  |       |  sbr  |       sbr = squareBottomRight
                        *   |_______|_______|_______|
                        mouseLocation = e1.getPoint();
                        Dimension defaultSquareDimension = new Dimension(50,50);
                        //current-player-location points
                        Point topLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY());
                        Point topRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY());
                        Point bottomLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY()+50);
                        Point bottomRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY()+50);
                        //four-squares-around-the-player points
                        //T = top, B = bottom, R = right, L = left
                        Point ptl = new Point((int)topLeft.getX()-50,(int)topLeft.getY()-50);
                        Point ptr = new Point((int)topRight.getX(),(int)topRight.getY()-50);
                        Point pbl = new Point((int)bottomLeft.getX()-50,(int)bottomLeft.getY());
                        Point pbr = new Point((int)bottomRight.getX(),(int)bottomRight.getY());
                        //ghosts
                        stl = new Rectangle (ptl, defaultSquareDimension);
                        str = new Rectangle (ptr, defaultSquareDimension);
                        sbl = new Rectangle (pbl, defaultSquareDimension);
                        sbr = new Rectangle (pbr, defaultSquareDimension);
                        Rectangle player = new Rectangle(topLeft, defaultSquareDimension);     //rectangle of player
                        if (stl.contains(mouseLocation) && !hoveringVillain(stl))
                             actors[8] = new Actor("ghost", ptl);
                             else actors[8] = null;
                        if (str.contains(mouseLocation) && !hoveringVillain(str))
                             actors[9] = new Actor("ghost", ptr);
                             else actors[9] = null;
                        if (sbl.contains(mouseLocation) && !hoveringVillain(sbl))
                             actors[10] = new Actor("ghost", pbl);
                             else actors[10] = null;
                        if (sbr.contains(mouseLocation) && !hoveringVillain(sbr))
                             actors[11] = new Actor("ghost", pbr);
                             else actors[11] = null;
                   private boolean hoveringVillain(Rectangle r)
                        boolean onVillain = false;
                        for (int i=1; i<=5 && !onVillain; i++) onVillain = actors.getRect().equals(r);
                        return onVillain;
              /** Mouse-click settings.
              Note: only usable after moving the mouse. /
              addMouseListener (new MouseAdapter()
                   /** When the mouse button is clicked */
                   public void mouseClicked (MouseEvent me)
                        mouseClickedAction(me);
         private boolean hoveringVillain(Rectangle r)
              boolean onVillain = false;
              for (int i=1; i<=5 && !onVillain; i++) onVillain = actors[i].getRect().equals(r);
              return onVillain;
         public void mouseClickedAction(MouseEvent me)
              System.out.println("Point: "+me.getX()+","+me.getY());
              if (waitingForPlayer) {
                   //causes error if the mouse wasn't moved uptil now. try it.
                   mouseLocation = me.getPoint();
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
              } else MiscTools.shout("Wait for the computer to take action!");
              if (actors[0].getPoint().getY() == 0){
                   for (int i=1; i<=5; i++){
                             actors[i].setStatus("angry");
                   //repaint();
                   MiscTools.shout("Game Over! You Won!");
         /** First thing the Game Panel does.
         Initiating the variables, and then looping: updating, painting and sleeping./
         public void run() {
    Thread thisThread = Thread.currentThread();                                                  //Enables the restart action (two threads needed).
    init();                                                                                                                                            //Initialize the variables.
    while (animator == thisThread && working){                                                  //While the current thead is the game's and it's "on",
                   think();                                                                                                                             //Update the variables,
                   repaint();                                                                                                                             //Paint the stuff on the panel,
                   try {Thread.sleep(5);} catch (InterruptedException ex) {}                    //And take a wee nap.
         /** Initializing the variables.*/
         private void init()
              currentVillain = 1;
              working = true;                                                                                //Make the game ready for running.
              inSight = false;
              actors = new Actor[12];                                                                      //Six actors: player and 5*villains.
              actors[0] = new Actor("player", 200, 450);                                             //The first actor is the player.
              int yPoint = 50;                                                                           //The Y location of the villains (first row).
              /* ACTORS ON TOP, RIGHT, LEFT
              actors[1] = new Actor ("villain", 0, 350);
              actors[2] = new Actor ("villain", 0, 150);
              actors[3] = new Actor ("villain", 50, 0);
              actors[4] = new Actor ("villain", 250, 0);
              actors[5] = new Actor ("villain", 450, 0);
              actors[6] = new Actor ("villain", 450, 200);
              actors[7] = new Actor ("villain", 450, 400);
              /* ACTORS ON TOP*/
              for (int i=1; i<actors.length-4; i++){                                                  //As long as it doesnt go above the array...
                   actors[i] = new Actor ("villain", yPoint, 0);                                   //init the villains
                   actors[i].setStatus("idle");
                   yPoint+=100;                                                                           //and advance in the Y axis.
         /** Updating variables.*/
         private void think()
              if (!waitingForPlayer){
                   //initialize
                   int playerX = (int)actors[0].getPoint().getX();
                   int playerY = (int)actors[0].getPoint().getY();
                   boolean moved = false;
                   wholeBoard = new Rectangle(0,0,500,500);     //needed to check whether an actor is inside the board
                   //for (int in = 0; in<=5; in++) actors[in].setStatus("idle"); //"formatting" the actor's mood
                   if (playerY <= 1000) inSight = true;     //first eye contact between the player and villains.
                   int closestVillainLevel = 0;
                   int[] vills = closestVillain();
                   int moveCounter = 0;
                   if (inSight) {
                        while (!moved){               //while none of the villains made a move
                        moveCounter++;
                        if (moveCounter == 5) moved = true;
                        else{
                             currentVillain = vills[closestVillainLevel];
                             int villainX = (int)actors[currentVillain].getPoint().getX();
                             int villainY = (int)actors[currentVillain].getPoint().getY();
                             //clearing stuff up before calculating things
                             boolean playerIsBelowVillain = playerY > villainY;
                             boolean playerIsAboveVillain = playerY < villainY;
                             boolean playerIsOnSameRowAsVillain = playerY == villainY;
                             boolean playerIsToVillainsRight = playerX > villainX;
                             boolean playerIsToVillainsLeft = playerX < villainX;
                             boolean playerIsOnSameColumnAsVillain = playerX == villainX;
                             //System.out.println("\n-- villain number "+currentVillain+" --\n");
                             int xToAdd = 0, yToAdd = 0;
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             if (legalPoint(futurePoint)){
                                  moveActor(actors[currentVillain], futurePoint);
                                  moved = true;
                                  //System.out.println("\nVillain "+currentVillain+" is now at "+actors[currentVillain].getPoint());
                             else closestVillainLevel=circleFive(closestVillainLevel);
                        } //end of else
                        } //end of while
                        //currentVillain = circleFive(currentVillain); //obsolete
                   } //end of ifInSight
                   waitingForPlayer = true;
         private boolean legalPoint(Point fp)
              return (wholeBoard.contains(fp) && !onPeople(fp) && legalSquare(fp));
         private boolean legalSquare(Point p)
              if ( (p.getX()==0 || p.getX()%100==0) && (p.getY()/50)%2!=0 ) return true;
              if ( (p.getX()/50)%2!=0 && (p.getY()==0 || p.getY()%100==0) ) return true;
              return false;
         //return the closest villain to the player, by its level of distance.
         public int[] closestVillain()
              //System.out.println("Trying to find the closest villain...");
              double[] gaps = new double[5];     //the distances array
              //System.out.println("The villains' distances are: ");
              for (int i=0; i<5; i++){
                   gaps[i] = distanceFromPlayer(actors[i+1].getPoint());     //filling the distances array
                   //System.out.print(gaps[i]+", ");
              int[] toReturn = new int[5];
              double smallestGapFound;
              double[] arrangedGaps = smallToLarge(gaps);
              for (int level=0; level<5; level++){
                   smallestGapFound = arrangedGaps[level];
                   for (int i=1; i<=5; i++){
                        if (smallestGapFound == distanceFromPlayer(actors[i].getPoint())){
                             toReturn[level] = i;
              return toReturn;
         private double[] smallToLarge(double[] nums)
              //System.out.println("\nArranging array... \n");
              double[] newArray = new double[5];
              int neweye = 0;
              double theSmallestOfTheArray;
              for (int i=0; i<nums.length; i++){
                   theSmallestOfTheArray = smallest(nums);
                   //System.out.println("\t\t>> Checking whether location "+i+" ("+nums[i]+") is equal to "+theSmallestOfTheArray);
                   if (nums[i] == theSmallestOfTheArray && nums[i]!=0.0){
                        //System.out.println("\t\t>> Adding "+nums[i]+" to the array...");
                        newArray[neweye] = nums[i];
                        //System.out.println("\t\t>> Erasing "+nums[i]+" from old array...\n");
                        nums[i] = 0.0;
                        neweye++;
                        i=-1;
              /*System.out.print("\nDONE: ");
              for (int i=0; i<newArray.length; i++)
                   System.out.print("["+newArray[i]+"] ");
              System.out.println();*/
              return newArray;
         private double smallest (double[] nums)
                   //System.out.print("\tThe smallest double: ");
                   double small = 0.0;
                   int j=0;
                   while (j<nums.length){               //checking for a starting "small" that is not a "0.0"
                        if (nums[j]!=0.0){
                             small = nums[j];
                             j = nums.length;
                        } else j++;
                   for (int i=1; i<nums.length; i++){
                        if (small>nums[i] && nums[i]!=0.0){
                             small = nums[i];
                   //System.out.println(small+".");
                   return small;
         private double distanceFromPlayer(Point vp)
              Point pp = actors[0].getPoint(); //pp=plaer's point, vp=villain's point
              double x = Math.abs(vp.getX() - pp.getX());
              double y = Math.abs(vp.getY() - pp.getY());
              return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
         private int circleFive(int num)
                   if (num>=5) return 0;
                   else return num+1;
         private boolean onPeople(Point p)
              for (int jj=0; jj<=5; jj++)
                   if (jj!=currentVillain && p.equals(actors[jj].getPoint()))
                        return true;
              return false;
         /** Painting the game onto the Game Panel.*/
         public void paintComponent(Graphics g)
              Graphics2D graphics = (Graphics2D)g;                                                            //Reset the graphics to have more features.
              //draw bg
              graphics.setColor(Color.white);                                                                                //"format" the panel.
              graphics.fillRect(0,0,500,500);
         char squareType = 'f';                                                                                                    //First square's type (stand or fall).
         for (int height=0; height<PHEIGHT; height=height+SQUARESIZE){     //Painting the matrix bg.
                   for (int width=0; width<PWIDTH; width=width+SQUARESIZE){
                        if (squareType=='f') {                                                                                               //If a "fall" is to be drawn,
                             ih.paint(graphics, "fallpng", new Dimension(width,height));          //Draw a non-animated image to bypass white stuff.
                             ih.paint(graphics, "fall", new Dimension(width,height));               //Draw the water animation.
                             squareType = 's';                                                                                                    //Make the next square a "stand".
                        } else if (squareType=='s'){                                                                                //If a "stand" is to be drawn,
                             ih.paint(graphics, "stand", new Dimension(width,height));          //Draw the ground image,
                             squareType = 'f';                                                                                                    //and make the next square a "fall".
                   if (squareType=='f') squareType = 's';                                                                 //After finishing a row, switch again so
                   else squareType = 'f';                                                                                                    // the next line will start with the same type (checkers).
              for (int i=actors.length-1; i>=0; i--){                                                                           //Draw the actors on the board.
                   if (actors[i]!=null)
                        ih.paint(graphics, actors[i].currentImage(), actors[i].getPoint());
         /** Restart the game.
         Or, in other words, stop, initialize and start (again) the animator thread and variables./
         public void restart()
              System.out.println("\n\n\nRESTARTING GAME\n\n\n");
              animator = null;                                                                                                                   //Emptying the thread.
              init();                                                                                                                                                 //Initializing.
              animator = new Thread(this);                                                                                     //Re-filling the thread with this panel's process.
              animator.start();                                                                                                                   //launch "run()".
         protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");

Maybe you are looking for

  • PowerMac G5 replaced by Intel Duo?

    Does anyone (besides Apple) have any idea when the world might see them finish out their transition to the Intel Duo with a replacement to the dual/quad G5 desktop machines?

  • Vector mutations

    Hi everyone, I have a question about Vector (content) mutations. Suppose I have a simple Node object: public class Node &nbsp&nbsp&nbsppublic String name; &nbsp&nbsp&nbsppublic Node(String name) &nbsp&nbsp&nbsp{ &nbsp&nbsp&nbsp&nbsp&nbsp&nbspthis.nam

  • Cfthread of coldfusion on different systems-windows and RedHat

    Recently I use cfthread writing a multithread samples. Each thread ask a http request.When I run this cfc file with coldfusion9 on windows, it runs well. Then I run the same cfc file on coldfusion9 on linux(RedHat and centOS), unfortunately, it seems

  • Read extended File Info of a jpg-file from a digital camera (recorded date etc.)

    Viewing stored digital pictures in the Windows Explorer or with Google Picasa you can get additional Informations from the picture file: recorded date camera name / type etc. How can I acces the informations with Labview

  • Sql trace active

    Dear  all I am activated the sqltrace ,and seen the sqltrace file how can find out the error in sql trace file ,how we can get the error ,how we can analyis the sql trace file . please guide and advise   . what is means of the coluring in a sql trace