Initially I had wrongly designed a swing app gui which used static methods in the main method.
Then I realised I could've done it better. I've designed a rough outline of the app which might be correct per se, but maybe not optimized. I also decided to make the app thread-safe.
Here's an outline:
public class MyApp { JMenuBar myMenuBar = null; JToolBar myToolBar = null; JMenuItem myMenuItem1 = null; JMenuItem myMenuItem2 = null; JPanel northPanel = null; public JPanel createNorthPanel() { northPanel = new JPanel(); northPanel.add(createMenuBar()); northPanel.add(createToolBar()); return northPanel; } // similarly, create 'west', 'center', 'east' and 'south' panels public JMenuItem createMenuItem(String text, char mnemonic, String keyStrokeRepresentation) { JMenuItem newMenuItem = new JMenuItem(); // set respective properties... return newMenuItem; } public JMenuBar createMenuBar() { myMenuBar = new JMenuBar(); myMenuBar.add(myMenuItem1 = createMenuItem("MyMenuItem1", 'M', "control M")); myMenuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { // take some action here... } } // similarly, create other menu items return myMenuBar; } public static void main(String args[]) { // implementing thread safety... Runnable runner = new Runnable() { public void run() { JFrame mainFrame = new JFrame(); MyApp appInstance = new MyApp(); mainFrame.add(appInstance.createNorthPanel(), BorderLayout.NORTH); // similarly, create 'west', 'center', east' and 'south' panels... mainFrame.add(appInstance.createWestPanel(), BorderLayout.WEST); mainFrame.add(appInstance.createCenterPanel(), BorderLayout.CENTER); mainFrame.add(appInstance.createEastPanel(), BorderLayout.EAST); mainFrame.add(appInstance.createSouthPanel(), BorderLayout.SOUTH); mainFrame.setVisible(true); mainFrame.setSize(400, 300); } }; EventQueue.invokeLater(runner); } }
Is everything all right with the code, or can it be better optimized? Plz overlook the length of the code. It's rather long, I admit. Thanks.