我正在创建一个“GUI”应用程序,旨在使代码清晰,并将这些“GUI”组件分成类(你会在下面看到我的意思),现在菜单栏很好,但我我现在想知道,因为我想为他们实现 ActionListener,最好在哪个类中执行,例如在菜单栏类的这种情况下,在他的类中,或者在 Main 中实现动作侦听器,而不是实现抽象方法会使用我们想要执行动作的方法吗?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public final class Main extends JFrame {
private MenuBar menuBar;
public Main() {
setTitle("GUI");
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initGUI();
}
public void initGUI() {
menuBar = new MenuBar(this);
// this is last update before I started posting this, I decided to
// access exitMenu variable and than to addActionListener to it from a here, which is currently not working
menuBar.exitMenu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new Main();
}
}
菜单栏类:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public final class MenuBar {
public JMenu newMenu;
public JMenu aboutMeMenu;
public JMenu exitMenu;
public MenuBar(JFrame jFrame) {
JMenuBar menubar = new JMenuBar();
initNew(menubar);
initAboutMe(menubar);
initExit(menubar);
jFrame.setJMenuBar(menubar);
}
public void initNew(JMenuBar menubar) {
newMenu = new JMenu("New");
menubar.add(newMenu);
}
public void initAboutMe(JMenuBar menubar) {
aboutMeMenu = new JMenu("About Me");
menubar.add(aboutMeMenu);
}
public void initExit(JMenuBar menubar) {
exitMenu = new JMenu("Exit");
menubar.add(exitMenu);
}
}