Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在GUI Jbutton中链接新函数?_Java_Swing_User Interface_Jbutton - Fatal编程技术网

Java 如何在GUI Jbutton中链接新函数?

Java 如何在GUI Jbutton中链接新函数?,java,swing,user-interface,jbutton,Java,Swing,User Interface,Jbutton,这是我的JButton,如何将新函数链接到它? 按功能,我的意思是当你点击主页按钮时,它会引导你进入系统/程序的主页。如果按功能,你指的是点击按钮后要执行的一段代码,你必须为按钮编写一个ActionListener 基本上,您可以定义动作监听器,并在监听器的actionPerformed方法中插入您想要执行的代码 bhome = new JButton("Home"); bhome.setFont(font); bhome.setFocusPainted(false); bhome.setSi

这是我的JButton,如何将新函数链接到它?
按功能,我的意思是当你点击主页按钮时,它会引导你进入系统/程序的主页。

如果按功能,你指的是点击按钮后要执行的一段代码,你必须为按钮编写一个ActionListener

基本上,您可以定义动作监听器,并在监听器的actionPerformed方法中插入您想要执行的代码

bhome = new JButton("Home");
bhome.setFont(font);
bhome.setFocusPainted(false);
bhome.setSize(100, 25);
bhome.setLocation(70, 30);
bhome.addActionListener(this);
panel.add(bhome);

最简单、更易理解

从ActionListener调用您的函数!同时提供适当的(完整的相关)代码。你的代码毫无意义。可能是重复的
JButton bhome = new JButton("Home");
bhome.addActionListener(new HomeListener());

class HomeListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        // Do whatever you want to do
    }
}
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
}