The Artima Developer Community
Sponsored Link

Java Answers Forum
Help with Java Applet Needed

9 replies on 1 page. Most recent reply: May 27, 2004 6:33 AM by twc

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 9 replies on 1 page
Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Help with Java Applet Needed Posted: May 23, 2004 1:39 AM
Reply to this message Reply
Advertisement
HI

I have created a JApplet to which I add an JPanel. Within that JPanel I have added a Canvas and another JPanel with various buttons on. Now the problem: If I just add the Canvas and the buttonPanel to the JPanel, the buttons work, and the applet does what it suppose to do, but the layout is not quiet right. When I set the layout (I have used a BorderLayout), the buttons don't work, and the applet won't repaint. What's going on? How do I sort this out? Any help would be greatly appreaciated.


twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Help with Java Applet Needed Posted: May 24, 2004 6:51 AM
Reply to this message Reply
You need to post your code. You have probably made some subtle mistake, but there is no way to tell what it is just from your description of the problem.

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Help with Java Applet Needed Posted: May 24, 2004 11:56 PM
Reply to this message Reply
// Philip Foulkes - 603F2534 - May 2004
// A simple Applet of a variation of a Langton's Ant
// If line 85 (setLayout (new BorderLayout()) is taken out the code works fine but the presentation is not so great.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class LangtonsAntPanel extends JPanel
{
	private static final Color GRAY  = Color.GRAY;
	private static final Color WHITE = Color.WHITE;
	private static final Color RED   = Color.RED;
	
	private static final int NORTH = 0;
	private static final int EAST = 1;
	private static final int SOUTH = 2;
	private static final int WEST = 3;
	
	private int height = 20;			//no of blocks high
	private int width = 20;				//no of blocks wide
	private static final int BLOCKSIZE = 20;	//the size of each block
	
	private AntCanvas antCanvas;
	private	Color[][] grid;				//store the color of each square
	private Ant ant;				//represent the ant
		
	private Timer timer;				//timer
	private int DELAY = 200;			//timer delay
	
	//buttons
	private JPanel buttonPanel;
	private JButton nextButton, runButton, stopButton, resetButton;
	
	//lables and textfields
	private JPanel inputPanel;
	private JLabel gridSizeLabel, redSquaresLabel, whiteSquaresLabel;
	private JTextField gridSizeTextField, redSquaresTextField, whiteSquaresTextField;
	
	public LangtonsAntPanel ()
	{
		//*****************************************************
		//buttonPanel
		buttonPanel = new JPanel ();
		buttonPanel.setLayout(new GridLayout(1,4));
		
		nextButton = new JButton ("Next");
		nextButton.addActionListener (new NextButtonListener());
		buttonPanel.add (nextButton);
		
		runButton = new JButton ("Run");
		runButton.addActionListener (new RunButtonListener());
		buttonPanel.add (runButton);
		
		stopButton = new JButton ("Stop");
		stopButton.addActionListener (new StopButtonListener());
		buttonPanel.add (stopButton);
		
		resetButton = new JButton ("Reset");
		resetButton.addActionListener (new ResetButtonListener());
		buttonPanel.add (resetButton);
		//*****************************************************
		
		//*****************************************************
		//inputPanel
		inputPanel = new JPanel (new GridLayout (2, 3));
		gridSizeLabel = new JLabel ("Grid Size");
		redSquaresLabel = new JLabel ("No. of Red Squares");
		whiteSquaresLabel = new JLabel ("No. of White Squares");
		
		gridSizeTextField = new JTextField (new Integer(height).toString());
		redSquaresTextField = new JTextField ("0");
		whiteSquaresTextField = new JTextField ("0");
		
		inputPanel.add (gridSizeLabel);
		inputPanel.add (redSquaresLabel);
		inputPanel.add (whiteSquaresLabel);
		
		inputPanel.add (gridSizeTextField);
		inputPanel.add (redSquaresTextField);
		inputPanel.add (whiteSquaresTextField);
		//*****************************************************
		
		antCanvas = new AntCanvas (width, height);
		
		setLayout (new BorderLayout()); 
		add (buttonPanel, BorderLayout.NORTH);
		add (antCanvas, BorderLayout.CENTER);
		add (inputPanel, BorderLayout.SOUTH);
		
		timer = new Timer (DELAY, new GoAntListener());
	}
	
	public void paintComponent (Graphics g)
	{
		super.paintComponent(g);
		antCanvas.update(g);
	}
	
	//changes the size of the canvas 
	//the size is obtained from the JTextField
	private void changeCanvasSize ()
	{
		int dim = new Integer(gridSizeTextField.getText()).intValue();
		height = width = dim;
		antCanvas = new AntCanvas (dim, dim);
	}
	
	private class AntCanvas extends Canvas
	{
		AntCanvas(int w,int h)
		{
		    	grid = new Color[w][h];
		    
		    	for (int r = 0; r < grid.length; r++)
		    	{
		    		for (int c = 0; c < grid[r].length; c++)
		    		{
		    			grid[r][c] = GRAY;
		    		}
			}
			
			randomColors();
			
			ant = new Ant ();
			
			//random initial x position of ant
			ant.x = (int)(Math.random() * width);
			ant.x *= BLOCKSIZE;
			ant.x += (BLOCKSIZE / 2);
			
			//random initial y position of ant
			ant.y = (int)(Math.random() * height);
			ant.y *= BLOCKSIZE;
			ant.y += (BLOCKSIZE / 2);
			
			//random initial direction of the ant
			ant.dir = (int)(Math.random() * 4);
		}
		
		//inserts red and white blocks in random spaces.
		//the number of squares is determined from the JTextFields
		private void randomColors ()
		{
			int red = new Integer(redSquaresTextField.getText()).intValue();
			int white = new Integer(whiteSquaresTextField.getText()).intValue();
			
			//draw red squares
			for (int i = 0; i < red;)
			{
				int r = (int)(Math.random() * width);
				int c = (int)(Math.random() * height);
				
				if (grid[r][c] != RED)
				{
					grid[r][c] = RED;
					i++;
				}
				
				if (i >= (height * width))
					i = red;
			}
			
			//draw white squares
			for (int i = 0; i < white;)
			{
				int r = (int)(Math.random() * width);
				int c = (int)(Math.random() * height);
				
				if (grid[r][c] != WHITE && grid[r][c] != RED)
				{
					grid[r][c] = WHITE;
					i++;
				}
				
				if (i >= ((height * width) - red))
					i = white;
			}
		}
		
       		public void paint (Graphics g)
		{
			//draw grid
   			for (int r = 0; r < grid.length; r++)
		    	{
		    		for (int c = 0; c < grid[r].length; c++)
		    		{
		    			g.setColor (grid[r][c]);
		    			g.fillRect (r * BLOCKSIZE, c * BLOCKSIZE, BLOCKSIZE, BLOCKSIZE);
		    		}
		    	}
		    	
		    	//draw ant
		    	ant.draw(g);
		}
		
		public void update (Graphics g)
		{
			paint(g);
		}
	}
		
	private class Ant
	{
		public int x;	//x co-ord of ant
		public int y;	//y co-ord of ant
		public int dir;	//direction of ant
		
		private static final int DIAM = BLOCKSIZE;	//diameter of ant
		
		//change the dir of the ant and give the new color
		//of the curret block
		public void changeDirection ()
		{
			Color col = grid[(ant.x - BLOCKSIZE / 2) / BLOCKSIZE][(ant.y - BLOCKSIZE / 2) / BLOCKSIZE];
			
			if (col == GRAY)
			{
				if (dir == WEST)
					dir = NORTH;
				else
					dir++;
				
				col = WHITE;
			}
			else if (col == WHITE)
			{
				if (dir == NORTH)
					 dir = WEST;
				else
					dir--;
					
				col = RED;
			}
			else if (col == RED)
			{	
				if (dir == NORTH || dir == SOUTH)
					dir++;
				else
				{
					if (dir == EAST)
						dir = WEST;
					else if (dir == WEST)
						dir = EAST;
				}
				
				col = GRAY;
			}
			
			grid[(ant.x - BLOCKSIZE / 2) / BLOCKSIZE][(ant.y - BLOCKSIZE / 2) / BLOCKSIZE] = col;	
		}
		
		//move the ant in the appropriate direction
		public void move ()
		{
			switch (dir)
			{
				case NORTH: y -= BLOCKSIZE; break;
				case EAST:  x += BLOCKSIZE; break;
				case SOUTH: y += BLOCKSIZE; break;
				case WEST:  x -= BLOCKSIZE; break;
			}
			
			//check to see if ant goes over the edge of the canvas
			if (x > width * BLOCKSIZE)
				x = BLOCKSIZE/2;
			else if (x < 0)
				x = (width * BLOCKSIZE) - (BLOCKSIZE/2);
			
			if (y > height * BLOCKSIZE)
				y = BLOCKSIZE/2;
			else if (y < 0)
				y = (height * BLOCKSIZE) - (BLOCKSIZE/2);
		}
		
		//draw ant
		public void draw (Graphics g)
		{
			g.setColor (Color.black);
			g.fillOval (x - (DIAM/2), y - (DIAM/2), DIAM, DIAM);
		}
	}
	
	private class GoAntListener implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			//change the direction of the ant and change the color of the square
		    	ant.changeDirection();
		    	ant.move();	
			repaint();
		}
	}
	
	private class NextButtonListener implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			//change the direction of the ant and change the color of the square
		    	ant.changeDirection();
		    	ant.move();	
			repaint();
		}
	}
	
	private class RunButtonListener implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			timer.start();
		}
	}
	
	private class StopButtonListener implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			timer.stop();
		}
	}
	
	private class ResetButtonListener implements ActionListener
	{
		public void actionPerformed (ActionEvent e)
		{
			timer.stop();
			changeCanvasSize();
			repaint();
		}
	}
}

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Help with Java Applet Needed Posted: May 26, 2004 11:14 AM
Reply to this message Reply
Philip,

I don't see anything wrong in the code that you posted, but I didn't see anything about an applet there either. Maybe the problem is in the applet code.

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Help with Java Applet Needed Posted: May 26, 2004 12:32 PM
Reply to this message Reply
This is my applet code:
The only problem exists when I put the line setLayout (new BorderLayout()); in.
import javax.swing.*;
 
public class LangtonsAntApplet extends JApplet
{
	public void init ()
	{
		getContentPane().add (new LangtonsAntPanel());
	}
}

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Help with Java Applet Needed Posted: May 26, 2004 12:36 PM
Reply to this message Reply
The same problem exists if I create a new LangtonsAntPanel and put into a JFrame.

Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: Help with Java Applet Needed Posted: May 26, 2004 4:28 PM
Reply to this message Reply
Here is your working code. Your code had minor problems. In fact, you have only painting problem.

1. From paintComponent() method of main applet you were
calling update() of canvas. You don't need to do that.
Canvas would have repainted itself.
2. You don't need to pass graphics object which is for main applet to Canvas in it its update() method call as described in STEP 1.

3. By correcting mistakes in STEP 1 and 2 , I was able to run your applet. It works fine.

4. Why do you mix swing and awt components? I mean, why did you use canvas at all. You can use JPanel instead. Mixing swing and awt components has paiting problems sometimes.

5. In the following code, I have replaced the Canvas by JPanel. The following code is yours with the folloing changes
a) See the paintComponent() method of main applet
b) Canvas replaced by JPanel
c) Commented update() method of old Canvas

package test;
// Philip Foulkes - 603F2534 - May 2004
// A simple Applet of a variation of a Langton's Ant
// If line 85 (setLayout (new BorderLayout()) is taken out the code works fine but the presentation is not so great.
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class LangtonsAntPanel extends JPanel
{
        private static final Color GRAY  = Color.GRAY;
        private static final Color WHITE = Color.WHITE;
        private static final Color RED   = Color.RED;
 
        private static final int NORTH = 0;
        private static final int EAST = 1;
        private static final int SOUTH = 2;
        private static final int WEST = 3;
 
        private int height = 20;			//no of blocks high
        private int width = 20;				//no of blocks wide
        private static final int BLOCKSIZE = 20;	//the size of each block
 
        private AntCanvas antCanvas;
        private	Color[][] grid;				//store the color of each square
        private Ant ant;				//represent the ant
 
        private Timer timer;				//timer
        private int DELAY = 200;			//timer delay
 
        //buttons
        private JPanel buttonPanel;
        private JButton nextButton, runButton, stopButton, resetButton;
 
        //lables and textfields
        private JPanel inputPanel;
        private JLabel gridSizeLabel, redSquaresLabel, whiteSquaresLabel;
        private JTextField gridSizeTextField, redSquaresTextField, whiteSquaresTextField;
 
        public LangtonsAntPanel ()
        {
                //*****************************************************
                //buttonPanel
                buttonPanel = new JPanel ();
                buttonPanel.setLayout(new GridLayout(1,4));
 
                nextButton = new JButton ("Next");
                nextButton.addActionListener (new NextButtonListener());
                buttonPanel.add (nextButton);
 
                runButton = new JButton ("Run");
                runButton.addActionListener (new RunButtonListener());
                buttonPanel.add (runButton);
 
                stopButton = new JButton ("Stop");
                stopButton.addActionListener (new StopButtonListener());
                buttonPanel.add (stopButton);
 
                resetButton = new JButton ("Reset");
                resetButton.addActionListener (new ResetButtonListener());
                buttonPanel.add (resetButton);
                //*****************************************************
 
                //*****************************************************
                //inputPanel
                inputPanel = new JPanel (new GridLayout (2, 3));
                gridSizeLabel = new JLabel ("Grid Size");
                redSquaresLabel = new JLabel ("No. of Red Squares");
                whiteSquaresLabel = new JLabel ("No. of White Squares");
 
                gridSizeTextField = new JTextField (new Integer(height).toString());
                redSquaresTextField = new JTextField ("0");
                whiteSquaresTextField = new JTextField ("0");
 
                inputPanel.add (gridSizeLabel);
                inputPanel.add (redSquaresLabel);
                inputPanel.add (whiteSquaresLabel);
 
                inputPanel.add (gridSizeTextField);
                inputPanel.add (redSquaresTextField);
                inputPanel.add (whiteSquaresTextField);
                //*****************************************************
 
                antCanvas = new AntCanvas (width, height);
 
                setLayout (new BorderLayout());
                add (buttonPanel, BorderLayout.NORTH);
                add (antCanvas, BorderLayout.CENTER);
                add (inputPanel, BorderLayout.SOUTH);
 
                timer = new Timer (DELAY, new GoAntListener());
        }
 
        public void paintComponent (Graphics g)
        {
                super.paintComponent(g);
                //antCanvas.update(g);
                //antCanvas.repaint();
        }
 
        //changes the size of the canvas
        //the size is obtained from the JTextField
        private void changeCanvasSize ()
        {
                int dim = new Integer(gridSizeTextField.getText()).intValue();
                height = width = dim;
                antCanvas = new AntCanvas (dim, dim);
        }
 
        private class AntCanvas extends JPanel//Canvas
        {
                AntCanvas(int w,int h)
                {
                            grid = new Color[w][h];
 
                            for (int r = 0; r < grid.length; r++)
                            {
                                    for (int c = 0; c < grid[r].length; c++)
                                    {
                                            grid[r][c] = GRAY;
                                    }
                        }
 
                        randomColors();
 
                        ant = new Ant ();
 
                        //random initial x position of ant
                        ant.x = (int)(Math.random() * width);
                        ant.x *= BLOCKSIZE;
                        ant.x += (BLOCKSIZE / 2);
 
                        //random initial y position of ant
                        ant.y = (int)(Math.random() * height);
                        ant.y *= BLOCKSIZE;
                        ant.y += (BLOCKSIZE / 2);
 
                        //random initial direction of the ant
                        ant.dir = (int)(Math.random() * 4);
                }
 
                //inserts red and white blocks in random spaces.
                //the number of squares is determined from the JTextFields
                private void randomColors ()
                {
                        int red = new Integer(redSquaresTextField.getText()).intValue();
                        int white = new Integer(whiteSquaresTextField.getText()).intValue();
 
                        //draw red squares
                        for (int i = 0; i < red;)
                        {
                                int r = (int)(Math.random() * width);
                                int c = (int)(Math.random() * height);
 
                                if (grid[r][c] != RED)
                                {
                                        grid[r][c] = RED;
                                        i++;
                                }
 
                                if (i >= (height * width))
                                        i = red;
                        }
 
                        //draw white squares
                        for (int i = 0; i < white;)
                        {
                                int r = (int)(Math.random() * width);
                                int c = (int)(Math.random() * height);
 
                                if (grid[r][c] != WHITE && grid[r][c] != RED)
                                {
                                        grid[r][c] = WHITE;
                                        i++;
                                }
 
                                if (i >= ((height * width) - red))
                                        i = white;
                        }
                }
 
                       public void paintComponent (Graphics g)
                {
                        //draw grid
                           for (int r = 0; r < grid.length; r++)
                            {
                                    for (int c = 0; c < grid[r].length; c++)
                                    {
                                            g.setColor (grid[r][c]);
                                            g.fillRect (r * BLOCKSIZE, c * BLOCKSIZE, BLOCKSIZE, BLOCKSIZE);
                                    }
                            }
 
                            //draw ant
                            ant.draw(g);
                }
                /*
                public void update (Graphics g)
                {
                        paint(g);
                }
        */
        }
 
        private class Ant
        {
                public int x;	//x co-ord of ant
                public int y;	//y co-ord of ant
                public int dir;	//direction of ant
 
                private static final int DIAM = BLOCKSIZE;	//diameter of ant
 
                //change the dir of the ant and give the new color
                //of the curret block
                public void changeDirection ()
                {
                        Color col = grid[(ant.x - BLOCKSIZE / 2) / BLOCKSIZE][(ant.y - BLOCKSIZE / 2) / BLOCKSIZE];
 
                        if (col == GRAY)
                        {
                                if (dir == WEST)
                                        dir = NORTH;
                                else
                                        dir++;
 
                                col = WHITE;
                        }
                        else if (col == WHITE)
                        {
                                if (dir == NORTH)
                                         dir = WEST;
                                else
                                        dir--;
 
                                col = RED;
                        }
                        else if (col == RED)
                        {
                                if (dir == NORTH || dir == SOUTH)
                                        dir++;
                                else
                                {
                                        if (dir == EAST)
                                                dir = WEST;
                                        else if (dir == WEST)
                                                dir = EAST;
                                }
 
                                col = GRAY;
                        }
 
                        grid[(ant.x - BLOCKSIZE / 2) / BLOCKSIZE][(ant.y - BLOCKSIZE / 2) / BLOCKSIZE] = col;
                }
 
                //move the ant in the appropriate direction
                public void move ()
                {
                        switch (dir)
                        {
                                case NORTH: y -= BLOCKSIZE; break;
                                case EAST:  x += BLOCKSIZE; break;
                                case SOUTH: y += BLOCKSIZE; break;
                                case WEST:  x -= BLOCKSIZE; break;
                        }
 
                        //check to see if ant goes over the edge of the canvas
                        if (x > width * BLOCKSIZE)
                                x = BLOCKSIZE/2;
                        else if (x < 0)
                                x = (width * BLOCKSIZE) - (BLOCKSIZE/2);
 
                        if (y > height * BLOCKSIZE)
                                y = BLOCKSIZE/2;
                        else if (y < 0)
                                y = (height * BLOCKSIZE) - (BLOCKSIZE/2);
                }
 
                //draw ant
                public void draw (Graphics g)
                {
                        g.setColor (Color.black);
                        g.fillOval (x - (DIAM/2), y - (DIAM/2), DIAM, DIAM);
                }
        }
 
        private class GoAntListener implements ActionListener
        {
                public void actionPerformed (ActionEvent e)
                {
                        //change the direction of the ant and change the color of the square
                            ant.changeDirection();
                            ant.move();
                        repaint();
                }
        }
 
        private class NextButtonListener implements ActionListener
        {
                public void actionPerformed (ActionEvent e)
                {
                        //change the direction of the ant and change the color of the square
                            ant.changeDirection();
                            ant.move();
                        repaint();
                }
        }
 
        private class RunButtonListener implements ActionListener
        {
                public void actionPerformed (ActionEvent e)
                {
                        timer.start();
                }
        }
 
        private class StopButtonListener implements ActionListener
        {
                public void actionPerformed (ActionEvent e)
                {
                        timer.stop();
                }
        }
 
        private class ResetButtonListener implements ActionListener
        {
                public void actionPerformed (ActionEvent e)
                {
                        timer.stop();
                        changeCanvasSize();
                        repaint();
                }
        }
}
 
 

babu

Posts: 2
Nickname: baburaju1
Registered: Apr, 2004

java exam dump 310-325 Posted: May 26, 2004 10:48 PM
Reply to this message Reply
pl

help me java dumps.



yours
babu

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Help with Java Applet Needed Posted: May 27, 2004 12:06 AM
Reply to this message Reply
Thank you for the help with the code. My reason for mixing the different types of components is purely from lack of experience.

Regards

Philip

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Help with Java Applet Needed Posted: May 27, 2004 6:33 AM
Reply to this message Reply
> Thank you for the help with the code. My reason for mixing
> the different types of components is purely from lack of
> experience.

Don't feel too bad. I have some experience and I did not know that mixing AWT and Swing components could cause problems. You learn something new every day.

Flat View: This topic has 9 replies on 1 page
Topic: Using/Automating Outlook with Java app Previous Topic   Next Topic Topic: test

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use