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

Similar Messages

  • Paint JPanel problem

    Hi All
    I have 2 classes
    class1. has a Jframe with a JPanel.
    class1 2. A Has a JPanel called contact
    I am calling class2 from class1.
    It is placing the the contact Panel onto the JPanel in class1 but does not show. If I resize class1 it the shows that it is there.
    I have tried repaint(); with out any luck
    any other help would be helpfull
    Thanks
    Craig

    Ok Here you go
    I have class1 witch is my main frame called Command class
    I have a menu class that has a jTree on it called Menu_Panel
    Then I have a class called DataClient which is the panel that I am have Problems with.
    Here is the Code
    This is the jbInit in the Command Class.
        mainPanel.setLayout(borderLayout3);
        mainPanel.setLayout(borderLayout4);
        topPanel = new Panel_Top();
        mainPanel.add(topPanel, BorderLayout.NORTH);
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
        setMenuItems();
        contentPane = (JPanel)this.getContentPane();
        contentPane.setLayout(borderLayout1);
        this.setSize(new Dimension(900, 600));
        this.setTitle("Frame Title");
        jMenuFile.add(jMenuFileExit);
        jMenuHelp.add(jMenuHelpAbout);
        jMenuBar1.add(jMenuFile);
        jMenuBar1.add(jMenuHelp);
        contentPane.add(mainPanel, BorderLayout.CENTER);
        mainPanel.add(menuPanel, BorderLayout.WEST);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(dataPanel, BorderLayout.CENTER);
        mainPanel.revalidate();
        this.setJMenuBar(jMenuBar1);
        fontResize();
        menuPanel.setDataPanel(dataPanel);   // This is where the Menu_Panel calls the show of DataPanel This is from the Menu_Panel at which point fires the menuPanel.setDataPanel(dataPanel); in the Command Class.
    /** Required by TreeSelectionListener interface. */
      public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();
        if (node != null) {
          fromMenu = tree.getLastSelectedPathComponent().toString();
          checkMenuNames ();
    public void checkMenuNames (){
      if(fromMenu.equals("Client")){
              dataPanel.showClient();
    }This is the DataPanel Class
    public class DataPanel
        extends JPanel {
      private DataClient dataClient;
      public void showClient() {
        //  dClient = new Data_Client();
    if (dataClient == null){
      System.out.println("This worked");
    dataClient = new DataClient();
    this.add(dataClient);
    }and this is the DataClient class
    public class DataClient  extends JPanel{
      XYLayout xYLayout1 = new XYLayout();
      JLabel jLabel1 = new JLabel();
      public DataClient() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jLabel1.setText("This is Client");
        this.setLayout(xYLayout1);
        this.add(jLabel1,    new XYConstraints(110, 95, 179, -1));
    }Hope you can help me :)
    Craig

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

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

  • Jsp and JPanel problem

    Hello. I've been to this forum many times, but have always been a bit gunshy about posting anything of my own. Now I have a problem I haven't seen before, so here goes. I have a JPanel in a java program that has all sorts of other componants added to it. I am trying to display the whole thing in a jsp page. This is what I am doing in the java file to return the image ("display" is the JPanel):
    public byte[] getImage(){
        int w = display.getWidth();
        int h = display.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        display.paint(img.createGraphics());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(img, "jpeg", os);
        return os.toByteArray();
    }and then in the jsp page I say:
    <%@ page contentType="image/jpeg" %>
    <%@ page import="myPackage.MyClass" %>
    <%
         MyClass picture = new MyClass();
         byte[] b = picture.getImage();
         OutputStream os;
         os = response.getOutputStream();
         os.write(b);
         os.flush();
    %>And the problem is that the page is displaying a blank JPanel and none of the componants that were added to it. If I save the the JPanel as a jpeg in the java program, though, it does contain all the componants, so I am not sure what I am doing wrong here. If there is some way to get the all the JPanel componants returned, that would be great to know. Thanks for any help.

    nope, that didn't work.
    Maybe I am going about solving the problem all wrong. The JPanel and its componants are kind of like a template. When a user of the system submits their information it automatically puts the data into the template and displays it on screen as a jpg. It works when I save the jpg as a file from the java program but not when i send the byte array to the jsp server. It just shows the blank panel....
    Is there a better way to go about doing this?

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

  • Urgent- Printing JPanel problem

    I want to print a JPanel by calling a Print utility class. JPanel is drawing with different shapes (Rectangle2D etc..)
    The problem is that I can only print the first page of the JPanel.
    My Print utility:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintUtilities {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    BookComponentPrintable printable1 = new BookComponentPrintable(componentToBePrinted);
    PageFormat pageFormat1 = printJob.pageDialog(printJob.defaultPage());
    Book book = new Book();
    book.append(printable1, pageFormat1);
    // Print the Book.
    printJob.setPageable(book);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    class BookComponentPrintable
    implements Printable {
    private Component mComponent;
    public BookComponentPrintable(Component c) {
    mComponent = c;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    else
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    mComponent.paint(g2);
    return Printable.PAGE_EXISTS;
    What did I do wrong? Thanks in advance !!!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Help!!! Please!!! jPanel problem.....

    Hi,
    I have MainFrame that contains jPanel1. ANd jPanel1 contains jPanel2, jPanel3, jPanel4.
    My problem is with jPanel2. jPanel2 contains jScrollPane.
    Let me just give tell you what i am doing.
    I wrote something which gets the image from database & displays the Multipage Tiff IMages in
    jScrollPane which is in jPanel2. I also have something which zooms the image from 10% to 120%.
    When i zoom the image to 30% the image is shown with only Vertical Scroll Bars. The image looks fine
    the first time its loaded. But when i move the vertical scroll bar the outside the image portion is shown
    with white and gray small areas each time i move the scroll bar.
    But when i zoom the image to 50% the image is shown with both scroll bars. SO when i scroll down or sideways
    I have no problem.
    Its only when i have vertical scroll bars.
    I have done repaint and validate on jPanel2 & jScrollPane but noting was solved.
    Any help or suggestions are always appreciated.
    Thanks in advance.

    Make sure you are calling invalidate() and validate() prior to the repaint. And since you are using a JPanel, try calling revalidate() as well. When ever I run into paint problems I just use trial an error on those 3 calls along with repaint() untill I find a combination that works. I really should spend 5 minutes figuring out which order to make these calls in and when but I have yet to do that :-(
    Bryan

  • Some two threaded image prepare and painting applet coordination problem

    hi all,
    i'm sure this multithreaded gui is complex but anyway. a simple producer&consumer type applet. there is one seperate thread preparing an offscreen image, and the main guy draws it on applet. i can not coordinate them, what's wrong i don't know. simply, applet starts a thread, which paints something on an offscreen image, and then tells to applet repaint(). anyway, here is the code, this small png files are a lot, idea is making a view on them, just imagine a big big png file divided into matrices. afterall this is not the important part. what i see on the screen is, if you ask, nothing.
    thanx,
    ozz
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.lang.reflect.Array;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MapViewer
         extends JFrame
         Image map[][];
         public MapViewer()
              int dimensions[] = { 58, 46 };
              map = (Image[][]) Array.newInstance(Image.class, dimensions);
              try
                   loadImages();
              catch(Exception e)
                   e.printStackTrace();
         public void loadImages()
              throws Exception
              for(int i=0; i<58; i++)
                   for(int j=0; j<46; j++)
                        StringBuffer sb = new StringBuffer();
                        sb.append("C:\\map\\");
                        sb.append(i+1);
                        sb.append("_");
                        sb.append(46-j);
                        sb.append(".png");
                        map[i][j] = Toolkit.getDefaultToolkit().getImage( sb.toString() );
         public void go()
              initComponents();
              show();
         private void initComponents()
              addWindowListener
                   new java.awt.event.WindowAdapter()
                        public void windowClosing(java.awt.event.WindowEvent evt)
                             exitForm(evt);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new MapPanel(), BorderLayout.NORTH);
              pack();
         private void exitForm(java.awt.event.WindowEvent evt)
              System.exit(0);
         public static void main(String args[])
              new MapViewer().go();
         private class MapPanel
              extends JPanel
              implements MouseMotionListener, Runnable
              private int north = 1;
              private int east = 2;
              private int south = 4;
              private int west = 8;
              private int direction;
              private Image model;
              private Boolean refreshModel = Boolean.TRUE;
              private Boolean modelReady = Boolean.FALSE;
              private Point start = new Point(200, 200);
              public MapPanel()
                   addMouseMotionListener(this);
                   new Thread(this).start();
              public synchronized Image requestImage()
                   return createImage(1600, 1600);
              public Dimension getMinimumSize()
                   return new Dimension(400, 400);
              public Dimension getPreferredSize()
                   return new Dimension(400, 400);
              public void paint(Graphics g)
                   synchronized(modelReady)
                        if(modelReady.booleanValue() == true)
                             g.drawImage(model, 0, 0, null);
                   g.setColor(Color.white);
                   g.fillRect(0, 0, 30, 10);
                   g.setColor(Color.black);
                   g.drawString(String.valueOf(direction), 0, 10);
              public void mouseDragged(MouseEvent e)
              public void mouseMoved(MouseEvent e)
                   Point p = e.getPoint();
                   findDirection(p);
              private void findDirection(Point p)
                   direction = 0;
                   if(p.x < 100)
                        direction |= west;
                   else if(p.x > 300)
                        direction |= east;
                   if(p.y < 100)
                        direction |= north;
                   else if(p.y > 300)
                        direction |= south;
              public void moveIt()
                   int px = 20;
                   int py = 20;
                   synchronized(refreshModel)
                        if(refreshModel.booleanValue() == true)
                             model = requestImage();
                             if(model == null || model.getGraphics() == null)
                                  return;
                             Graphics g = model.getGraphics();
                             for(int x=0; x < 4; x++)
                                  for(int y=0; y<4; y++)
                                       g.drawImage(map[px+x][py+y], x*200, y*200, null);
                             refreshModel = Boolean.FALSE;
                             modelReady = Boolean.TRUE;
    //               start.x -= 3;
    //               start.y -= 3;
              public void run()
                   while(true)
                        try
                             moveIt();
                             repaint();
                             Thread.currentThread().sleep(20);
                        catch(InterruptedException ie)

    Hi.
    The Graphics.drawImage method is asynchronyous, that may be the reason of the problem. Set an ImageObserver parameter in drawImage method, when drawing on an offscreen image. Count finished images and when all are done
    draw the big image on the screen.
    Alternatively you can call Toolkit.prepareImage method in a loop, after loadimages and wait until all images are loaded(true returned).

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

  • Border / paint and update problem

    Hi,
    I have written a simple GUI and have two problems:
    first, a white border is being displayed a the right, left and bottom side.
    Second: for testing purposes I am drawing a simple rectangle; I am starting at (1, 1) but it's actually being drawn maybe at (-5, -5). Sometimes it's not being drawn at all.
    Here is my code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.WindowConstants;
    public class MainWindow extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jPanel1;
         final static BasicStroke stroke = new BasicStroke(2.0f);
         public MainWindow() {
              initComponents();
         private void initComponents() {
              jPanel1 = new JPanel();
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              jPanel1.setBackground(new Color(153, 204, 255));
              jPanel1.setPreferredSize(new Dimension(1024, 768));
              getContentPane().add(jPanel1);
              pack();
         public void paint(Graphics g){
              update(g);
         public void update(Graphics g){
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(stroke);
              g2.draw(new Rectangle2D.Double(1, 1, 50, 50));
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainWindow().setVisible(true);
    }I am not sure about the paint / update method. I read the Swing tutorial and found examples where the drawing is being done in the update method... Does this have certain advantages?
    Thanks for your help!

    I still don't have it... where is my mistake?
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MainWindow extends JPanel {
         private static final long serialVersionUID = 1L;
         public MainWindow() {
              initComponents();
         private void initComponents() {
              JComponent face = new InitMainWindow();
              face.setPreferredSize( new Dimension(250, 250) );
              JFrame frame = new JFrame();
                    frame.setTitle("Test");
              frame.setBackground(new Color(153, 204, 255));
              frame.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent evt) {
                        mouseClick(evt);
              frame.pack();
              frame.setVisible( true );
         private void mouseClick(MouseEvent evt) {
              System.out.println("Click!");
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(Color.BLACK);
              g.drawLine(100, 100, 150, 150);
         public static void main(String args[]) {
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new MainWindow().setVisible(true);
    }

  • A strange JPanel problem

    i have a JPanel which have a picture as a background the problem is when i wnat to add a JLabel or JTextField into this JPanel it didnt word but it works for labels bat JLabels no???why??
    here u are the code
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    public class d extends Container
        JTextField text1,text2,text3,text4,text5,text6;
         ImageIcon icon ;
       public d()
    {  super();
       setLayout(null );                                                                         
        setBackground(Color.RED);                                                                                                 
        text1=new JTextField();
       text2=new JTextField();
       text3=new JTextField();
       text4=new JTextField();
       text5=new JTextField();
        text6=new JTextField();
        panel p=new panel();
       p.setBounds(10,10,500,500);
         p.setLayout(null);
         p.setOpaque(true);
    p.setBackground(Color.WHITE);
    text1.setBounds(160,30,100,20);
    p.add(text1);
    text2.setBounds(10,30,100,20);
      p.add(text2);
      text3.setBounds(300,30,100,20);
      p.add(text3);
      text4.setBounds(10,100,100,20);
      p.add(text4);
    text5.setBounds(160,100,100,20);
      p.add(text5);
      text6.setBounds(300,100,100,20);
      p.add(text6);
    JLabel l1=new JLabel("touti");
    l1.setBackground(Color.WHITE);
      l1.setBounds(10,10,80,15);
      add(p);
       class panel extends JPanel
           public  void paint(Graphics g) {
           super.paint(g);
           icon=new ImageIcon("c:/bachir.jpg");
            g.drawImage(icon.getImage(),0,0, this);
    public static void main(String args[])
       JFrame frm = new JFrame( "test panel back ground" );
            frm.setBounds( 100, 100, 800, 800 );
            frm.getContentPane().setLayout( new BorderLayout() );
        d pnl=new d();
            frm.getContentPane().add(pnl , BorderLayout.CENTER );
      frm.setIconImage(Toolkit.getDefaultToolkit().getImage("c:/java/oicon.gif"));
            frm.setVisible( true );
    }

    You seem to be mixing AWT and Swing. You should use all AWT or all Swing but not a mixture. Try changing
    public class d extends Container
    to
    public class d extends JPanel.
    P.S. Your choice of class name stinks! It does not describes the role the class plays and it does not meet the Sun recommended coding standards.
    Message was edited by:
    sabre150

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

Maybe you are looking for

  • FCC - Complex target hierarchy

    Hi There, I was implementing a scenario where I need to create multiple IDocs from one file (which I plan to do with IDoc bundling). But I came accros a 'issue': I have a flat file like this header x items trailer Nothing special so far, but because

  • Acrobat Form visibility

    Good morning. I hope this is the correct area. I have just created a form in Acrobat XI Pro. Form works great. I have added a "Clear Form" (reset a form) function, and also a "Submit form". Both buttons are set to "Visible but doesn't print". These b

  • Share reminders

    When "Reminders" was integrated to "Calendar", it was possible to share lists of tasks. Now it is impossible. I can't even change this property to my list that I'm sharing currently. I can't understand why this function has been downgraded...? Will t

  • To get current user through trigger

    Hi, I want audit trail through database trigger. But I noticed in trigger 'portal30.wwctx_api.get_user' is failed to parse. Is there any way to get the current user in trigger? Thanks, Sumita

  • Software would not recognise printer

    I am running OS X 10.9.4 in a MacBook Pro, Photoshop CC, and a Canon printer MG8220. I have installed the plug in Easy-PhotoPrint Pro that is advertised at the Canon site as fully supporting that printer. When I automate the plug in from Photoshop it