Im new to java and im trying to build a simple GUI with several buttons and drop down menus. Ive managed to get a working GUI but the real question is about the proper use of the actionListener method. In order to assign an action to a button i inserted each actionListener in its own class, this is the code:
public class GUI implements something
{
public static ClientGUI App;
private JFrame chatWin;
private JMenuBar menubar;
private JMenu x;
private JMenu y;
private JMenuItem exit;
private JMenuItem about;
public GUI()
{
/*
* some code and parameters
*/
//creating the menu bar
JMenuBar menubar = new JMenuBar();
chatWin.setJMenuBar(menubar);
JMenu x= new JMenu("menu1");
menubar.add(x);
JMenuItem exit = new JMenuItem("menu2");
x.add(exit);
JMenu y= new JMenu("Help");
menubar.add(help);
JMenuItem about = new JMenuItem("inner menu1");
y.add(about);
//action listener for the exit button
class exitaction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
exit.addActionListener(new exitaction());
//action listener for the about button
class aboutaction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//some code
}
}
}
public static void main (String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
App = new GUI();
}
});
}
}
Is that code is considered to be neat and correct? is there anything i could improve or need to change?
I follow the rule:
If the action implementation is great, I put in a inner class.
When short, i put in a anonymous class.
If it is used by other components, I extract to a top level class.