Java GUI programming with Swing

Document Sample
Java GUI programming with Swing Powered By Docstoc
					Java GUI programming
     with Swing


     Tim McKenna
     Seneca@York
               Java 2
          Swing Components


   Java Foundation Classes(JFC)
       - Java 2 Swing components
       - Java2D graphics classes
   the class JComponent(API)
   http://java.sun.com/products/jfc
   Swing Tutorial
   Swing Connection
           Swing Components


   button: JButton
   label: JLabel
   item selection:
    JCheckBox, JRadioButton, JToggleButton
   object selection:
    JComboBox, JList, JSpinner
   text: JTextField, JTextArea, JEditorPane,
    JFormattedTextField, JPasswordField
   menus: JMenuBar, JMenu, JMenuItem, ...
        Swing Components and Events


Event Source   Event Type Generated
JButton        ActionEvent

JTextField     ActionEvent (but don't listen for it)

JMenuItem      ActionEvent

JComboBox      ItemEvent, ActionEvent

JCheckBox      ItemEvent

JRadioButton   ItemEvent (but don't listen for it)

JList          ListSelectionEvent
               Swing Components


   Example(Online Reservation):
    • Reservation.java – listens to everything
    • ReservationTM.java – listens when it matters
   a key point is WHEN components should be listened to.
   components often do not need a listener
   components can be inspected for their state:
    •   JTextField.getText()
    •   JRadioButton.isSelected()
    •   JCheckBox.isSelected()
    •   JComboBox.getSelectedIndex()
              Swing Components



   Event Handling
       JRadioButton, JCheckBox: addItemListener( )

        ItemListener interface: itemStateChanged( )

                   ItemEvent: getStateChange( )
             Swing Components


   Event Handling
       JComboBox: addActionListener( ),

                 getSelectedItem( ),
                 getSelectedIndex( )

        JTextField:   addActionListener( )

                      ActionEvent:
                            getActionCommand( )
               Swing Components


   Swing Component: JList
   Example: JListDemo.java
   Inspect JList:
    • getSelectedIndex() - returns -1 if there is no selection.
    • getSelectedIndices() - empty array if nothing is selected
    • getSelectedValue() – returns null or object referred to in the
      list
    • isSelectionEmpty()
   Event Handling: addListSelectionListener()
    • javax.swing.event.ListSelectionListener interface
    • valueChanged()
           Swing Components


   Example: JTextDemo.java
   Swing Components:
       JTextField, JTextArea, JButton
   Event Handling:
   JTextField:
  addActionListener( ) vs. getText( )
 JTextArea: NO listener is registered!
  append( ), insert( ), setText( ),
  getSelectedText( ), getText( )

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:51
posted:7/13/2012
language:English
pages:9