Monday, March 5, 2007

Lecture 20

Menus

  • Important classes are

    • JMenuBar

    • JMenu

    • JMenuItem

  • all three of these are children of Component

  • all implement the add() method



Creating a Menu

  1. Create a Menubar

    • JMenuBar myMenuBar = new JMenuBar();

  2. Create menus and add them to the menubar

    • JMenu = new JMenu(“File”);

    • MyMenuBar.add(myMenu);

  3. Create and add menu items to the menu

    • JMenuItem Save = new JMenuItem(“Save”);

    • MyMenu.add(Save);

  4. Add action listener to each menu item

    • Save.addActionListener(this);

  5. Add menuBar to the JFrame

    • add (myMenuBar);//Bad!!

    • Set JMenuBar(myMenuBar); // Good!!





Windows and Inner Classes



  • For Complicated window components it makes sense to use inner classes

Recall:

Public class OuterClass;

{

Private class InnerClass

{

}

}

  • A complicated panel within a JFrame

Public class myJframe extends JFrame

{

Public myJPanel()

{//appearance of the panel;}

}

Public JFrame()

{

Add ( new myJPanel());

}

Private class myJPanel extends JPanel implements ActionListener

{

Public myJPanel()

{

JButton b = new JButton(“Button”);

b.addActionListener(this); /* this refers to myJPanel*/

add(b);

}

Public void ActionPerformed(ActionEvent e){…}



Text Field

  • JTextField

    • Constructor takes an integer size argument

    • JTextField t = newJTextField(20); /* 20 chars wide*/

      • public String getText()

      • public void setText(String S)

      • public void setEditable(boolean e)



No comments: