bhome = new JButton("Home");
bhome.setFont(font);
bhome.setFocusPainted(false);
bhome.setSize(100, 25);
bhome.setLocation(70, 30);
bhome.addActionListener(this);
panel.add(bhome);
这是我的 JButton,如何将新功能链接到它?通过功能,我的意思是当您单击主页按钮时,它会将您定向到系统/程序的主页。
bhome = new JButton("Home");
bhome.setFont(font);
bhome.setFocusPainted(false);
bhome.setSize(100, 25);
bhome.setLocation(70, 30);
bhome.addActionListener(this);
panel.add(bhome);
这是我的 JButton,如何将新功能链接到它?通过功能,我的意思是当您单击主页按钮时,它会将您定向到系统/程序的主页。
JButton bhome = new JButton("Home");
bhome.addActionListener(new HomeListener());
class HomeListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// Do whatever you want to do
}
}
如果通过函数,你的意思是点击按钮时要执行的一段代码,你必须为按钮编写一个 ActionListener。
基本上,您定义动作侦听器并将您想要执行的代码粘贴到侦听器的 actionPerformed 方法中。
btnYourButton= new JButton("Home");
btnYourButton.setFont(font);
btnYourButton.setFocusPainted(false);
btnYourButton.setSize(100, 25);
btnYourButton.setLocation(70, 30);
panel.add(btnYourButton);
btnYourButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e){
btnYourButton_actionPerformed(e);
}
});
// out side of the method where you declared your button
void btnYourButton_actionPerformed(ActionEvent e) {
//Your code goes here
}
最简单和更高的可理解性