mattbdean
mattbdean

Reputation: 2552

MouseEvent does not fire when implemented by a JPanel

Okay, so in this program I'm making, users will be able to create shortcuts to their favorite apps on their computer. My program will be kind of like a hub, I guess, for apps. I have a small problem though, which involves two classes: AppButton and AppButtonContainer. They both implement MouseListener, but AppButton extends JComponent and AppButtonContainer extends JPanel. Basically, when an AppButton is clicked, it sets a draws the border in a different color to make it look selected. Otherwise, it sets the border to the background color. When you double click it, it opens up the application specified. I have a method in AppButton to remove the focus, and therefore setting the border to the background color. In AppButtonContainer, there is a bit of code so that when, the panel is clicked, it removes the focus from the AppButton.

That's my problem, though. The AppButtonContainer doesn't realize that it's clicked. I'm thinking it has something to do with top level containers or something, but I'm not sure. Can anybody help?

EDIT: I found out that I didn't put the addMouseListener(this) in the constructor of the AppButtonContainer. Thank you for everyone who helped me clear up this problem and give me tips along the way :)

AppButtonContianer:

public class AppButtonContainer extends JPanel implements MouseListener {
private static final long serialVersionUID = 6485231881729120957L;
public List<AppButton> appButtons;
private static final Color BACKGROUND_COLOR = new Color(18, 18, 18);

public AppButtonContainer(List<AppButton> buttons) {
    this.appButtons = buttons;
    setLayout(new GridLayout(5, 5, 20, 20));
    addButtonsToPane();
}

private void addButtonsToPane() {
    List<AppButton> buttons = this.appButtons;
    for (int i = 0; i < buttons.size(); i++) {
        this.add(buttons.get(i));
    }
}

private void removeAllButtonFocus() {
    for (int i = 0; i < this.appButtons.size(); i++) {
        this.appButtons.get(i).removeFocus();
    }
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(BACKGROUND_COLOR);
    repaint();
}

@Override
public void mouseClicked(MouseEvent e) {
    System.out.println("Pane Clicked");
    removeAllButtonFocus();
}

    ...Other MouseEvent methods

Upvotes: 0

Views: 166

Answers (1)

Tharwen
Tharwen

Reputation: 3107

You can solve the problem at hand by putting addMouseListener(this) in the constructor for your AppButtonContainer class. Otherwise, it'll never pick up mouse events.

Generally, though, it's not good to turn your classes into mouselisteners like that. Perhaps try making an inner class to listen for mouse events and pass them to the AppButtonContainer instead.

Upvotes: 2

Related Questions