[英]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? 如何在Java Swing的
JFrame
父窗口中从JPanel
组件捕获动作事件?
I'm having a hard time trying to make a custom Component in Swing. 我很难尝试在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. 我得到的想法是在Swing中制作一个包含一些
JButton
的自定义JPanel,并在JFrame父窗口中捕获那些按钮上的动作事件。
I would like to implement the method addActionListener()
to my custom JPanel as if it were a button. 我想将方法
addActionListener()
应用于自定义JPanel,就好像它是一个按钮一样。
Do I have to extend from JComponent
instead of JPanel
? 我是否必须从
JComponent
而不是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
? 为什么要实现
addActionListener
而不是addMouseListener
?
¿Por qué quieres implementar addActionListener
en vez de addMouseListener
? ¿por quieres实现
addActionListener
和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) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.