120 likes | 249 Views
This lecture focuses on creating and managing menus in Java Swing applications, akin to using buttons. You will explore key components like JMenuBar, JMenu, and JMenuItem, alongside practical implementations. Using the provided example codes (FirstMenuFrame.java and SecondMenuFrame.java), we'll also discuss creating a MenuListener class to handle actions. The lecture emphasizes common layout managers like BorderLayout, FlowLayout, and GridLayout while troubleshooting frequent mistakes. Join us as we debug the code step-by-step to visualize menu interactions!
E N D
CS12420 - Lecture 02Menus Lynda Thomas ltt@aber.ac.uk
Menus are like Buttons • Use a Listener • Classes involved are: • JMenuBar • JMenu • JMenuItem • Warning: you may use words slightly differently!
MenuBar Menu MenuItem
Alternatively • You could use a separate MenuListener class • See SecondMenuFrame.java and MenuListener.java • Let’s step through code with debugger and see animation of what is happening...
1: new SecondMenuFrame() JFrame 4: new MenuListener(this) MenuListener SimpleFrame smFrame SecondMenuFrame 7: setPanelColor(Color.green) 3: new ColorPanel JMenu Colours JMenu Options JMenuItem Green JMenuBar JMenuItem JMenuItem JMenuItem JMenuItem 2: new JMenu* JPanel ColorPanel 6: select green: actionPerformed called 5: e.g. green.addActionListener(menuList)
Layout Managers • BorderLayout is default for JFrame • FlowLayout is default for JPanel • GridLayout: public TextPanel() { setLayout(new GridLayout(2,2,5,5)); //2 rows, 2 cols, spaces add (new JLabel("Amount: ")); inputField=new JTextField(8); add (inputField); add (new JLabel("Balance: ")); balanceField=new JTextField(8); add (balanceField); }
Possible mistakes: • Misspelling javax.swing in import • Forgetting setVisible(true) (done for you in SimpleFrame) • Forgetting the JFrame.EXIT_ON_CLOSE • If buttons etc. don’t work: • Have you got something Listening to the button? • Is there an appropriate action in actionPerformed? • Try just printing ‘they hit button X’
More components Radio buttons and Combo boxes ComboBoxDemo.java and RadioButtonDemo.java
In this lecture • We looked at menus In the next lecture we look at drawing