Painting in JPanel

I've an application done in Swing. I've a JPanel that I wish to paint some objects onto it (mainly circles & arcs). The circles will be stationary while the arcs will change location at fixed time-step.
Whenever I've the update of the new positions of the arcs, I'd need to redraw them on the panel. But my circles are stationary throughout.
What can I do to avoid redrawing the entire panel as it will take up too much time when my time-step is small.
Or is the method that I'm using wrong?

I've an application done in Swing. I've a JPanel that I wish to paint some objects onto it (mainly circles & arcs). The circles will be stationary while the arcs will change location at fixed time-step.
Whenever I've the update of the new positions of the arcs, I'd need to redraw them on the panel. But my circles are stationary throughout.
What can I do to avoid redrawing the entire panel as it will take up too much time when my time-step is small.
Or is the method that I'm using wrong?

Similar Messages

  • 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.

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

  • 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);
    /***********/

  • 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)

  • 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");

  • Painting with JPanel

    I have many classes, but only 3 matter. The problem is that my JPanel will not repaint. I tried using the repaint method, but it won't go to paintComponent.
    My main class is:
    package MainClass;
    * Main.java
    * Created on January 25, 2007, 5:05 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Wizardus
    import Graphics.*;
    import Utilities.*;
    import Loading.*;
    import java.util.Vector;
    import MainClass.*;
    public class Main {
        public Frame frame;
        public MenuListener listen;
        public String currMode;
        public String tmpFileName;
        public GWInterface gwi;
        public Loader load;
        public Vector stuffs;
        /** Creates a new instance of Main */
        public Main() {
            listen = new MenuListener(this);
            frame = new Frame(this);
            frame.addKeyListener(listen);
        public void newGame() {
            gwi = new GWInterface(false, false);
            Loader load = new Loader();
            //Campaign camp = load.loadCampaign("someone");
            currMode = "GAME";
            frame.updateStage(currMode);
            //Map mp = load.loadMap(camp.mapFile);
            //stuffs = load.loadStuff(camp.stuffFile);
            Map mp = load.loadMap("someone.gwmp");
            stuffs = load.loadStuff("someone.gws");
            //AIType ai = load.loadAI(camp.aiFile);
            //gwi.ai = ai;
            gwi.idLoaded(0);
            gwi.mapLoaded(mp);
            gwi.loadUp(stuffs);
            frame.removeKeyListener(listen);
            frame.addKeyListener(gwi);
            frame.addMouseListener(gwi);
            frame.addMouseMotionListener(gwi);
            gameLoop();
        public void gameLoop() {
            while(true) {
                gwi.update();
                //gwi.ai();
                frame.updateDisp();
                System.out.println("Hi in gameLoop");
                try {
                    Thread.sleep(50);
                } catch(Exception e) {
        public static void main(String[] args) {
            new Main();
    }The actual JFrame is called Frame:
    * Display.java
    * Created on January 30, 2007, 8:44 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package Graphics;
    * @author Wizardus-
    import Utilities.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    import MainClass.*;
    import java.util.Vector;
    import Utilities.Build.*;
    import Utilities.Troops.*;
    public class Frame extends JFrame{
        Main mana;
        public MainPanel panel;
        /** Creates a new instance of Display */
        public Frame(Main mana) {
            super("Something something");
            this.mana = mana;
            panel = new MainPanel(mana);
            panel.loadUp();
            getContentPane().add(panel);
            setSize(1000, 700);
            setVisible(true);
        public void updateDisp() {
            System.out.println("Hi in updateB");
            panel.updateDisp();
        public void updateStage(String stage) {
            panel.updateStage(stage);
    }Then, the JPanel called MainPanel is:
    * Display.java
    * Created on January 30, 2007, 8:44 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package Graphics;
    * @author Wizardus-
    import Utilities.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    import MainClass.*;
    import java.util.Vector;
    import Utilities.Build.*;
    import Utilities.Troops.*;
    public class MainPanel extends JPanel{
        String stage = "MENU";
        //BufferStrategy img;
        Main mana;
        Image backgroundDesign;
        Image panel;
        Image[] units;
        Image[] buildings;
        Image[] terrains;
        /** Creates a new instance of Display */
        public MainPanel(Main mana) {
            super();
            this.mana = mana;
            setSize(1000,700);
            setVisible(true);
        public void loadUp() {
            //createBufferStrategy(2);
            //img = getBufferStrategy();
            loadImg();
        public void loadImg() {
            //load the crap images!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! YEAH
        public void updateDisp() {
            System.out.println("Hi in updateA");
            repaint();
        public void updateStage(String stage) {
            this.stage = stage;
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            System.out.println("painting...");
            //Graphics g = img.getDrawGraphics();
    //        System.out.println(stage);
            if(stage.equals("MENU")) {
    //            //draw menu and menu's buttons
            } else if(stage.equals("GAME")) {
    //            //draw EVERYTHING in game
    //            //Step 0 draw map and background for panels
    //            g.drawImage(panel, 700, 0, null);
    //            g.drawImage(backgroundDesign, 690, 0, null);
    //            Map mp = mana.gwi.offmap;
    //            for(int i = 0; i < mp.terrain.length; i++) {
    //                for(int j = 0; j < mp.terrain.length; j++) {
    // Terrain curr = mp.terrain[i][j];
    // g.drawImage(terrains[curr.nameId], (mp.terrain.length * 15) + mana.gwi.mapX, (mp.terrain[i].length * 15) + mana.gwi.mapY, null);
    // //Step 1 draw buttons;
    // for(int i = 0; i < mana.gwi.defButtons.length; i++) {
    // g.drawRect(mana.gwi.defButtons[i].x, mana.gwi.defButtons[i].y, mana.gwi.defButtons[i].width, mana.gwi.defButtons[i].height);
    // g.drawString(mana.gwi.defButtons[i].txt, mana.gwi.defButtons[i].x, mana.gwi.defButtons[i].y);
    // for(int i = 0; i < mana.gwi.currButtons.length; i++) {
    // g.drawRect(mana.gwi.currButtons[i].x, mana.gwi.currButtons[i].y, mana.gwi.currButtons[i].width, mana.gwi.currButtons[i].height);
    // g.drawString(mana.gwi.currButtons[i].txt, mana.gwi.currButtons[i].x, mana.gwi.currButtons[i].y);
    //Step 2 draw units of each "Stuff" and the buildings;
    for(int i = 0; i < mana.gwi.stuff.size(); i++) {
    Stuff currStuff = (Stuff)mana.gwi.stuff.get(i);
    // for(int j = 0; j < currStuff.buildings.size(); j++) {
    // Buildings currBuild = (Buildings)currStuff.buildings.get(j);
    // g.drawImage(buildings[currBuild.nameId], (int)currBuild.x, (int)currBuild.y, null);
    for(int j = 0; j < currStuff.troops.size(); j++) {
    Soldier currSold = (Soldier)currStuff.troops.get(j);
    //g.drawImage(units[currSold.nameId], (int)currSold.x, (int)currSold.y, null);
    g.drawRect((int)(currSold.x), (int)(currSold.y), 20,20);
    //img.show();

    Thats because in your gameLoop you use Thread.sleep(...) which causes the GUI Thread to sleep. If the thread is sleeping then it never gets a chance to repaint itself.
    If you want you game to repaint itself then use a [url http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]Swing Timer to schedule the repainting and get rid of the Thread.sleep(..).

  • Painting on JPanel

    Hi,
    i managed to establish a MouseListener, so when i press on the graphArea (a JPanel) i can get the cooridinates. Now, based on these coordinates, i want to draw an Oval. I created a class, trying to override the paint method and experimented a little, but all these have no effect...
    What can i do?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.Graphics;
    public class MainPanel extends JFrame
        /*  To make a local variable available to an 
         *  inner class, just save a copy of the variable as a
         *  final local variable.
        int clickedX;
        int clickedY;
        JPanel graphArea;  
        JPanel outPanel;
        JPanel inPanel;
        public MainPanel()
            //setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(new Dimension(800, 600));       
            setLayout(new BorderLayout());
            /*  setting up the area of the graph    */
            graphArea=new JPanel();       
            graphArea.addMouseListener(new MouseAdapter()
               public void mouseClicked (MouseEvent e)
                    clickedY=e.getY();
                    clickedX=e.getX();
                    graphArea.repaint();     
                    System.out.println("Mouse clicked X: "+clickedX+" Y:"+clickedY);               
            graphArea.setBorder(BorderFactory.createTitledBorder("graphArea"));
            graphArea.setPreferredSize(new Dimension(640, 340));       
            getContentPane().add(graphArea, BorderLayout.WEST);
            /* setting up the area of the outcoming connecrions */
            outPanel=new JPanel();
            outPanel.setBackground(Color.LIGHT_GRAY);
            addCheckBox(outPanel);
            outPanel.setBorder(BorderFactory.createTitledBorder("Outcoming Connections"));
            outPanel.setPreferredSize(new Dimension(120, 200));       
            getContentPane().add(outPanel,BorderLayout.PAGE_END);
            /* setting up the area of the incoming connecrions */
            inPanel=new JPanel();
            inPanel.setBackground(Color.LIGHT_GRAY);
            addCheckBox(inPanel);
            inPanel.setBorder(BorderFactory.createTitledBorder("Incoming Connections"));
            inPanel.setPreferredSize(new Dimension(160, 240));       
            getContentPane().add(inPanel,BorderLayout.LINE_END);
            setVisible(true);
        /*  provided, that num is even  */
        void addCheckBox(JPanel pane)
            int j=0;
            for (int i=0; i<4; i++)
                pane.add(new JCheckBox(Integer.toString(++j)));           
                pane.add(new JCheckBox(Integer.toString(++j)));
        class Oval extends JPanel
            public void paint(Graphics g)
                g.drawOval(clickedX,clickedY, 5,5);
        public static void main(String[] args)
            new MainPanel();
    }

    I created a class, trying to override the paint method and experimented a little, You don't override paint(..). I gave you a working example a couple of posting ago on how to do custom painting on a panel. I'm not going to waste time repeating myself.
    I'm not sure how you expect your oval to magically appear. You click on your graph area and tell it to repaint(..) itself, but you don't have any custom painting on your graphArea component.

  • Why won't the circles show? (Painting on JPanel)

    public class GUI extends JPanel{
    private Eye applet;
    private int SIZE = 500;
    private int innerSize = 100;
    private int middleSize = 300;
    private int outerSize = 500;
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel panel = new JPanel();
    Dimension dimension = new Dimension(SIZE,SIZE);
    Graphics gPanel;
    public GUI(Eye gui_applet) {
    try{
    applet = gui_applet;
    applet.setSize(SIZE,SIZE);
    applet.setVisible(true);
    panel.setMinimumSize(dimension);
    panel.setPreferredSize(dimension);
    panel.setLayout(borderLayout1);
    panel.setBackground(Color.cyan);
    applet.setContentPane(panel);
    gPanel=panel.getGraphics();
    paintCircles(gPanel);
    }catch(Exception e) { e.printStackTrace(); }
    }//gui
    public void paintCircles(Graphics g) {
    System.out.println("paintCircles in GUI called");
    g.drawString("boooo",20,20);
    gPanel.setColor(Color.red);
    gPanel.drawOval(200,200,innerSize,innerSize);
    gPanel.drawOval(100,100,middleSize,middleSize);
    gPanel.drawOval(0,0,outerSize,outerSize);
    gPanel.drawString("bo",30,30);
    panel.validate();
    } //gui
    Any help deeply appriciated. (Can't find any good answer in previous postings.)

    Try this, take out this lines:
    gPanel=panel.getGraphics();
    paintCircles(gPanel);
    }catch(Exception e) { e.printStackTrace(); }
    }//gui
    add this method
    public void paintComponent(Graphics g)
    suepr.paintComponent(g);
    paintCircles(g);
    Noah

  • Problem painting a JPanel

    I am making a card game for a project. The game features some human players versus some AI players. After a player makes a move, the game should take a short pause if the player was an AI player, so that the humans can see the cards played.
    Currently, the program zips by so fast after an AI move that it's not perceivable. I thought that throwing in a Thread.sleep(1000) after a call to repaint() would solve the problem. By doing this, however, I end up with a blank grey panel from the time the first AI player moves until the time it's a human's turn(at which time the executing thread dies and lets the human take over again).
    As some general information, the project is divided into a basic model/view split. A single thread of execution runs from the display to the model when a button is pressed, and the repaint is called by a callback from the model to the view. I have tried locating the sleep in different places(after the repaint, before the repaint, during AI move selection) with the same result.
    Any suggestions?

    You need to learn more about threading in swing. here is exellent chapter with example how to use timed paint in swing.
    http://developer.java.sun.com/developer/Books/javaprogramming/threads/chap9.pdf
    Here are links to articles in swing connection. You will be interested in topics about threads and using swing timer:
    http://java.sun.com/products/jfc/tsc/articles/
    It will greatly improve your app.
    Regards

  • Problems painting a JPanel component on a JFrame

    Hi.
    I've built a subclass of JPanel that has some controls on it, such as JPanels, JCheckBoxes, images, etc. I need to repaint this JPanel periodically because its contents are constantly changing.
    I have it added to a main JFrame (this JFrame has also other JPanels in other locations of its content pane), and when I try to repaint this JPanel, it does not seem to be double buffered, because it momentaneously repaints other parts of the window into the JPanel region, and after that it repaints what it should.
    I have tested a Panel instead of a JPanel to do the same task, and the Panel works fine.
    Basically, the code is:
    public class MyFrame extends JFrame
    JPanel myPanel = new JPanel();
    JPanel myPanel2 = new JPanel();
    JPanel myPanel3 = new JPanel();
    public MyFrame()
    getContentPane().setLayout(null);
    getContentPane().setSize(600, 400);
    myPanel.setBounds(0, 0, 200, 200);
    myPanel2.setBounds(0, 200, 200, 200);
    myPanel3.setBounds(0, 400, 200, 100);
    getContentPane().add(myPanel);
    getContentPane().add(myPanel2);
    getContentPane().add(myPanel3);
    // javax.swing.Timer to update myPanel
    Timer t = new Timer( 2000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    myPanel.repaint();
    t.start();
    I actually use othe class names and field names, but the structure is basically the same.
    Any idea of what am I doing wrong? Why Panels work fine in the same situation, into the same JFrame?
    Thank you.

    Try constructing your JPanels as doublebuffered then. (new JPanel(A layoutmanager, true)). The latter parameter is a boolean for creating a doublebuffered JPanel or not. Try with calling myPanel.revalidate() after repainting.

  • Paint component inside JPanel

    Hi guys,
    I will start with the original problem and get to the only option that seems possible before hardcoding everything.
    I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
    Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
    But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
    So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.

    You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

Maybe you are looking for

  • IPad no longer printing to HP B210a printer

    iPad stopped printing to an Hp b210 a printer. It worked this morning, I changed all the ink cartridges this afternoon and now it no longer prints to it. I shut the printer off as the HP help suggested. My husbands ipad prints to it as well as my lap

  • 3g iPad in Spain

    Hi, I'm travelling to Spain next weeks, expecting to be there for a couple of months. Does anyone know the best way to set up 3G access on my iPad whilst I'm there? Points to note: . Roaming charges too expensive, so using a UK contract/tariff is not

  • Database Initialization Error

    Hi, I was trying to initialize my DB and I get this error "Upgrade Wizard did not complete successfully. Please examine the log file for details and restart the Siebel application to attempt the upgrade again. " Where to look for these log files ? Wh

  • TopLink ADF binding named query parameterized

    What is the easieast way to execute parameterized named queries using TopLink and ADF databinding? How to pass parameters?

  • Need to stop fire fox from asking me to update my browser how do I do this

    Fire Fox keeps telling me I need to update my browser, newer browser is not compatible with my banking system. I updated and could not access my bank account, so I went back to previous version but I keep getting notice to update it is very annoying,