JFrame监听JPanel里的clicked事件

Falleyes 2015-10-12 11:34:33
现在有个JFrame 叫mainFrame,有个自定义的JPanel 叫numPanel,在mainFrame的特定位置会通过构造函数new一个numPanel,这样,numPanel就被mainFrame包含在里面了。
numPanel里面有个按钮,点击它,触发了对应的clicked事件。现在在JFrame里面有个函数,只要监听到numPanel里面的那个clicked事件触发,就会执行。应该怎样实现这个监听呢?
...全文
284 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JButtonTest {
public static void main(String[] args) {
MainFrame mf = new MainFrame();
}
}

class MainFrame extends JFrame{
public MainFrame(){
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);

add(new NumPane());
}
}

class NumPane extends JPanel{
public NumPane(){
JButton button = new JButton("OK");
add(button);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("I had clicked the OK button!");
}
});

JButton button2 = new JButton("Cancel");
add(button2);
button2.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("I had clicked the Cancel button!");
}
});

}
}
  • 打赏
  • 举报
回复
JButton类继承了Component的addMouseListener方法,给按钮添加鼠标监听器(可以用MouseAdapter包装),有个mouseClicked
方法,你可以实现,当鼠标点击时的动作

你也可以添加一个addActionListener监听器,更简单

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧