Skip to main content

Mouselistener interferes with JButton listener

2 replies [Last post]
posdef
Offline
Joined: 2009-03-08

Hello,

I am writing an applet that has an action listener for a JButton and a mouse listener for a JPanel. Each listener works by itself when the other listener is not included in the code. However, when I include both of them only the mouse listener works. How do I fix it?

Here is my code. GameOfLifePanel extends JPanel.

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

public class GameOfLifeApplet extends JApplet {
private static final int ROWS = 50, COLS = 50;
private static final int CELL_SIZE = 10;
private GameOfLifePanel lifePanel;

public void init() {

getContentPane().setLayout(new BorderLayout());

// set up life panel
lifePanel = new GameOfLifePanel(ROWS, COLS, CELL_SIZE);
lifePanel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
lifePanel.changeCell(x, y);
}
});
getContentPane().add(lifePanel, BorderLayout.NORTH);

// set up button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
JButton goButton = new JButton("Go");
goButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
lifePanel.start();
}
});

buttonPanel.add(goButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);

}

}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17

It works for me, changing it to a JPanel and System.out. I also added the lifePanel to the CENTER, so maybe you are not clicking on the panel, but below it?

posdef
Offline
Joined: 2009-03-08

I still couldn't get the applet to work but it works as a JPanel with a main method. I think there is something fundamental about how applets work that I don't understand.

Thanks for your help!