简体   繁体   中英

Catch action events from a JPanel component in a JFrame parent window

How to catch action events from a JPanel component in a JFrame parent window in Java Swing?

I'm having a hard time trying to make a custom Component in Swing.

The idea I got is making a custom JPanel in Swing which contains some JButton , and catching the action events over those buttons in a JFrame parent window.

I would like to implement the method addActionListener() to my custom JPanel as if it were a button.

Do I have to extend from JComponent instead of JPanel ?

I really appreciate your help and your time.

package pizzeria.interfaz;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class AplicacionCliente extends JFrame{

    public AplicacionCliente() {

        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        PanelMenu panelmenu = new PanelMenu(); //PanelMenu extends JPanel and has my buttons


        JButton bot = new JButton("Prueba");        
        bot.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("Botonazo!");

            }}); 


        contentPane.add(bot);
        contentPane.add(panelmenu, BorderLayout.LINE_END);

    }
}

Why you want implement addActionListener instead of addMouseListener ?

¿Por qué quieres implementar addActionListener en vez de addMouseListener ?

EDIT: check this code, may works

public class AplicacionCliente extends JFrame implements MouseListener{

public AplicacionCliente() {

    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    this.setVisible(true);

    PanelMenu panelmenu = new PanelMenu(); //PanelMenu extends JPanel and has my buttons


    JButton bot = new JButton("Prueba");
    bot.addMouseListener(this);
    bot.setName("bot");

    contentPane.add(bot);
    contentPane.add(panelmenu, BorderLayout.LINE_END);

}

@Override
public void mouseClicked(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
    if(((JButton)e.getSource()).getName().compareToIgnoreCase("bot")==0){
        System.out.println("Botonazo!!");
    }
}

@Override
public void mouseReleased(MouseEvent e) {
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM