Chapter 08 Advanced Gui New
Chapter 08 Advanced Gui New
Objectives
Create menus using components JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem and JRadioButton
ISB16003-OOP Jan2010
Swing components
In previous lesson, you were introduced to only two components (JButton, JTextField) and several containers (JFrame and JPanel) Here are some of the Swing components :
JButton JCheckBoxMenuItem JMenu JRadioButtonMenuItem JLabel JTextComponent JTextField JComboBox JTextArea JList JScrollBar JSlider JToggleButton JCheckBox JRadioButton JPasswordField JComponent AbstractButton JMenuItem
: :
Creating menus
Java provides 5 classes that implement menus : 1) JMenuBar 2) JMenu 3) JMenuItem 4) JCheckBoxMenuItem 5) JRadioButtonMenuItem Menu bar hold the menus Menu hold the menu items (select or toggle on/off) A menu item can be an instance of 3, 4 or 5 above
ISB16003-OOP Jan2010
.
JFrame
separator
The menu item generates ActionEvent. Your program must implement the ActionListener and actionPerformed handler to respond to the menu selection. The following is an example :
public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.getSource() instanceof JMenuItem) { if (New equals(actionCommand)) respondToNew(); //responds to New menu item else : }
ISB16003-OOP Jan2010
ISB16003-OOP Jan2010
ISB16003-OOP Jan2010
Done by example
(B)
String actionCommand = e.getActionCommand If (user clicks JButton) if (e.getSource() instanceof JButton) handle button event if(Add.equals(actionCommand)) else calculate(+); if (user select JMenuItem) else handle menu item event if(Substract.equals(actionCommand)) calculate(-); : ISB16003-OOP Jan2010
(C)
Obtain num1 and num2
private void calculate (char operator){ int num1 = (Integer.parseInt(jtfNum1.getText().trim())); int num2 = (Integer.parseInt(jtfNum1.getText().trim())); int result = 0; switch(operator) { case +: result= num1+num2; break; : } jtfResult.setText(String.valueOf(result);
Note : Dont forget to repeat code (B) for handling menu item event
9)
ISB16003-OOP Jan2010