Sign in to follow this  
agm_ultimatex

[java] addActionListener in JApplet

Recommended Posts

I have two buttons generated in a JPanel in the init() method of my JApplet. I need to add an actionListener that I created (public class ButtonListener implements ActionListner) to the class that extends JApplet.

Share this post


Link to post
Share on other sites
What i do is i let my main class (Japplet) implement ActionListener, and then write a function actionPerformed()

public void actionPerformed(ActionEvent e){
if(e.getSource()==my_button){
// do some stuff
}
}

In yo init() method, you should add an action listener to the button (my_button.addActionListener(this);)
It should work for a JApplet though i never tried using one for a game.
Some people prefer designing their own action listeners, but thats a bit harder to do.

Share this post


Link to post
Share on other sites
Ah that worked thanks. Now with the logic i applied to what happens when the button is pushed, the program freezes lol. The program draws little squares when the mouse is pressed, and draws them to the current mouse location (each mouse click it adds a square to an ArrayList). The button labeled start in my program is meant to take an oval thats in the center, and make it move to each point/square (so it follows the squares much like a path).

I'll post some code when i have a chance later.

Share this post


Link to post
Share on other sites
When I run my program, I get the following exception:
Exception in thread "AWT-EventQueue-1" java.lang.OutOfMemoryError: Java heap space
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.TaskQueue.add(Unknown Source)
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)
at FieldCanvas.move(FieldCanvas.java:98)
at PathTest.move(PathTest.java:39)
at PathTest.actionPerformed(PathTest.java:51)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)

Heres my source code:

//PathTest.java

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class PathTest extends JApplet implements ActionListener
{
private FieldCanvas fc;
public PathTest()
{

}

public void init()
{
Container container = getContentPane();
this.setSize(300,340);
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
JButton startButton = new JButton("Start");
JButton clearButton = new JButton("Clear");
startButton.addActionListener(this);
clearButton.addActionListener(this);
content.add(startButton);
content.add(clearButton);

fc = new FieldCanvas();
container.add(fc, BorderLayout.NORTH);
container.add(content, BorderLayout.SOUTH);
}
public void stop()
{

}

public void move()
{
fc.move();
}

public void clear()
{
fc.clear();
}
public void actionPerformed(ActionEvent e)
{
String whichButton = e.getActionCommand();
if(whichButton.equals("Start"))
{
move();
}
else if(whichButton.equals("Clear"))
{
clear();
}
}
}

//FieldCanvas.java


import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Timer.*;

public class FieldCanvas extends Canvas
{
private Ball b;
private Point p;
private Graphics g;
private ArrayList<Point> points;

//used for a timer
private Timer timer;
private TimerTask task;
private int interval;
private int currentX, currentY;
public FieldCanvas()
{
setBackground(Color.WHITE);
setSize(300,300);
b = new Ball(150, 150, 10, 10);
points = new ArrayList<Point>();

interval = 100;
timer = new Timer();

this.addMouseListener(new InputListener(this));
}

public void drawPoint(int x, int y)
{
p = new Point(x, y, 5, 5);
points.add(p);
repaint();
}

public void paint(Graphics g)
{
b.draw(g);
this.g = g;
Iterator<Point> it = points.listIterator();
while(it.hasNext())
{
Point temp = it.next();
temp.draw(g);
}
}

public void move()
{
Iterator<Point> it = points.listIterator();
int x, y, ballX, ballY;
while(it.hasNext())
{
Point temp = it.next();
x = temp.getX();
y = temp.getY();
ballX = b.getX();
ballY = b.getY();
do
{
if(x != ballX)
{
if(ballX < x)
{
x += 1;
}
else if(ballX > x)
{
x -= 1;
}
}
if(y != ballY)
{
if(ballY < y)
{
y += 1;
}
else if(ballY > y)
{
y -= 1;
}
}
setCurrentX(x);
setCurrentY(y);
task = new TimerTask()
{
public void run()
{
b.setX(currentX);
b.setY(currentY);
repaint();
}
};
timer.schedule(task,0,interval);
}while (x != ballX && y != ballY);
System.out.println("x: "+ x + " y: " + y);
}
}

public void clear()
{

}

public void setCurrentX(int currentX)
{
this.currentX = currentX;
}
public void setCurrentY(int currentY)
{
this.currentY = currentY;
}
}

//Shape.java

import java.awt.*;

public abstract class Shape
{
private int x, y, sizeX, sizeY;

public Shape(int x, int y, int sizeX, int sizeY)
{
this.x = x;
this.y = y;
this.sizeX = sizeX;
this.sizeY = sizeY;
}

public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setSizeX(int x)
{
this.x = x;
}
public void setSizeY(int y)
{
this.y = y;
}
public int getSizeX()
{
return sizeX;
}
public int getSizeY()
{
return sizeY;
}

public abstract void draw(Graphics g);
}

//Ball.java

import java.awt.*;

public class Ball extends Shape
{
public Ball(int x, int y, int sizeX, int sizeY)
{
super(x, y, sizeX, sizeY);
}

public void draw(Graphics g)
{
g.fillOval(getX(), getY(), getSizeX(), getSizeY());

}
}

//Point.java

import java.awt.*;

public class Point extends Shape
{
public Point(int x, int y, int sizeX, int sizeY)
{
super(x, y, sizeX, sizeY);
}

public void draw(Graphics g)
{
g.fillRect(getX(), getY(), getSizeX(), getSizeY());
}
}

//InputListener.java

import java.awt.event.*;

public class InputListener implements MouseListener
{
private FieldCanvas fc;
public InputListener(FieldCanvas fc)
{
this.fc = fc;
}

public void mouseEntered(MouseEvent e)
{

}
public void mouseExited(MouseEvent e)
{

}
public void mousePressed(MouseEvent e)
{
fc.drawPoint(e.getX(), e.getY());
e.consume();
}
public void mouseReleased(MouseEvent e)
{

}
public void mouseClicked(MouseEvent e)
{

}
}

//ButtonListener.java

import java.awt.event.*;

public class ButtonListener implements ActionListener
{
private PathTest pt;
public ButtonListener(PathTest pt)
{

}

public void actionPerformed(ActionEvent e)
{
String whichButton = e.getActionCommand();
if(whichButton.equals("Start"))
{
pt.move();
}
else if(whichButton.equals("Clear"))
{
pt.clear();
}
}
}



Share this post


Link to post
Share on other sites
Welcome to real-world Java. Someone once told me they thought the learning curve for Java Swing was a wall. So get ready to learn a whole bunch of stuff...

Not everything I am going to mention is causing this problem, but they are all things you should be aware of...

1. Don't mix AWT and Swing. Here is a great article explaining the problems.

http://java.sun.com/products/jfc/tsc/articles/mixing/

You have a JApplet (Swing), and you a putting a Canvas (AWT) into it.

JApplet - Swing
JCanvas - Swing
Applet - AWT
Canvas - AWT

Either use an Applet and Canvas, or a JApplet and JCanvas. This may not be causing you trouble now, but someday it will, and if you are not aware of the problems it causes, it could take a long time to figure out what the problem is.

2. Here is the move method, reformatted to take up less space. It looks like your logic for for moving x to ballx is not correct. If ballx is less than x, you add one to x???


// move method
Iterator<Point> it = points.listIterator();
int x, y, ballX, ballY;
while(it.hasNext()) {
Point temp = it.next();
x = temp.getX();
y = temp.getY();
ballX = b.getX();
ballY = b.getY();
do {
if(x != ballX) {
if(ballX < x) {
x += 1;
} else if(ballX > x) {
x -= 1;
}
}
if(y != ballY) {
if(ballY < y) {
y += 1;
} else if(ballY > y) {
y -= 1;
}
}
setCurrentX(x);
setCurrentY(y);
task = new TimerTask() {
public void run() {
b.setX(currentX);
b.setY(currentY);
repaint();
}
};
timer.schedule(task,0,interval);
} while (x != ballX && y != ballY);
System.out.println("x: "+ x + " y: " + y);
}



3. The reason you are getting an out-of-memory error is because you never leave the do loop, which continues to add timer tasks faster than it can run the tasks, and the timer runs out of space. Another aproach to this is to put all your drawing code in the paint method.


private boolean moving = false;

//in paint

// update position if moving...
if( moving ) {
if at square
select next square

calculate dx and dy
x += dx; // only once per paint
y += dy; // only once per paint
}

// draw everything here

repaint();



This means you would change your ActionListener to look something like this, which is a lot easier to understand...

public void actionPerformed(ActionEvent e){
moving = !moving; // toggle moving...
}


So when you click the button, you just toggle moving flag. In the paint method, which is constantly redrawing the scene, you only move when moving it true. Then you need to do everything in paint, but only one step each time paint is called. You pick the first point, and keep adjusting x and y until you get there, but you let each step get drawn so you see it.

Hope that helps...


Share this post


Link to post
Share on other sites
Quote:
Original post by Glass_Knife
Welcome to real-world Java. Someone once told me they thought the learning curve for Java Swing was a wall. So get ready to learn a whole bunch of stuff...

Not everything I am going to mention is causing this problem, but they are all things you should be aware of...

1. Don't mix AWT and Swing. Here is a great article explaining the problems.

http://java.sun.com/products/jfc/tsc/articles/mixing/

You have a JApplet (Swing), and you a putting a Canvas (AWT) into it.

JApplet - Swing
JCanvas - Swing
Applet - AWT
Canvas - AWT

Either use an Applet and Canvas, or a JApplet and JCanvas. This may not be causing you trouble now, but someday it will, and if you are not aware of the problems it causes, it could take a long time to figure out what the problem is.

2. Here is the move method, reformatted to take up less space. It looks like your logic for for moving x to ballx is not correct. If ballx is less than x, you add one to x???

*** Source Snippet Removed ***

3. The reason you are getting an out-of-memory error is because you never leave the do loop, which continues to add timer tasks faster than it can run the tasks, and the timer runs out of space. Another aproach to this is to put all your drawing code in the paint method.

*** Source Snippet Removed ***

This means you would change your ActionListener to look something like this, which is a lot easier to understand...
*** Source Snippet Removed ***
So when you click the button, you just toggle moving flag. In the paint method, which is constantly redrawing the scene, you only move when moving it true. Then you need to do everything in paint, but only one step each time paint is called. You pick the first point, and keep adjusting x and y until you get there, but you let each step get drawn so you see it.

Hope that helps...


#1. Thanks, I wasn't aware of the conflicts there. Along with your other points on changes, I'll have a look tonight, see what i can get working.

#2. Yes that is correct. If the ball has a lesser x position(ballX) aka. more left of the point, it moves further to the right(+1).

I'm using a canvas as something needs to generate the appropriate space for the drawing area. As I said in #1, i'll change it around a bit. Try a JCanvas for instance.

Share this post


Link to post
Share on other sites
I'm switching it to AWT, as I do not know of a Graphics equivalent for swing.

I'm currently trying to find how to appropriately initilize the container. As i currently have:
public void init()
{
Container container = getContentPane();
this.setSize(300,340);
...

getContentPane(); is no longer valid.

Share this post


Link to post
Share on other sites
AWT Frames do not have content panes, so you just add your contents directly to the frame. But you can make the code function almost exactly the same by just changing:

Container container = getContentPane();

to:

Container container = new Panel();
this.add(container);

Greggles

Share this post


Link to post
Share on other sites
My code for PathTest.java is as follows, but nothing shows. Please help

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;

public class PathTest extends Applet implements ActionListener
{
private FieldCanvas fc;
public PathTest()
{

}

public void init()
{
this.setSize(300,340);
Container mainPanel = new Panel();
//mainPanel.setLayout(new FlowLayout());

Panel content = new Panel();
content.setLayout(new FlowLayout());
Button startButton = new Button("Start");
Button clearButton = new Button("Clear");
startButton.addActionListener(this);
clearButton.addActionListener(this);
content.add(startButton);
content.add(clearButton);

fc = new FieldCanvas();
mainPanel.add(fc, BorderLayout.NORTH);
mainPanel.add(content, BorderLayout.SOUTH);
}
public void stop()
{

}
public void paint(Graphics g)
{

}
public void move()
{
fc.move();
}

public void clear()
{
fc.clear();
}
public void actionPerformed(ActionEvent e)
{
String whichButton = e.getActionCommand();
if(whichButton.equals("Start"))
{
move();
}
else if(whichButton.equals("Clear"))
{
clear();
}
}
public void update (Graphics g)
{
paint(g);
}

}

Share this post


Link to post
Share on other sites
I think you forgot to add "mainPanel" to the applet, so here is the corrected code:


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;

public class PathTest extends Applet implements ActionListener
{
private FieldCanvas fc;
public PathTest()
{

}

public void init()
{
this.setSize(300,340);
Container mainPanel = new Panel();
//mainPanel.setLayout(new FlowLayout());

Panel content = new Panel();
content.setLayout(new FlowLayout());
Button startButton = new Button("Start");
Button clearButton = new Button("Clear");
startButton.addActionListener(this);
clearButton.addActionListener(this);
content.add(startButton);
content.add(clearButton);

fc = new FieldCanvas();
mainPanel.add(fc, BorderLayout.NORTH);
mainPanel.add(content, BorderLayout.SOUTH);

this.add(mainPanel);//Add the mainPanel to the applet!
}
public void stop()
{

}
public void paint(Graphics g)
{

}
public void move()
{
fc.move();
}

public void clear()
{
fc.clear();
}
public void actionPerformed(ActionEvent e)
{
String whichButton = e.getActionCommand();
if(whichButton.equals("Start"))
{
move();
}
else if(whichButton.equals("Clear"))
{
clear();
}
}
public void update (Graphics g)
{
paint(g);
}

}

Share this post


Link to post
Share on other sites
Quote:
Original post by greggles
I think you forgot to add "mainPanel" to the applet, so here is the corrected code:

*** Source Snippet Removed ***


I figured it was something simple, thank you :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this