Component-Based Software Engineering GUI Basics Paul J Krause
Swing Overview Components in the Abstract Windowing Toolkit (AWT) rely on the local platform’s GUI capabilities Most Swing components are light-weight components - not “weighed-down” by the local platform’s GUI capabilities
Swing Overview java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent add( ) setlayout( ) setBorder( ) setOpaque( ) setToolTipText( ) paint( ) repaint( )
GUI Building in Swing Need at least one top-level container This is the root of a “containment hierarchy” this consists of all the Swing components that appear within that container this consists of all the Swing components that appear within that container Often, the root will be a Jframe
JFrame
Pattern for Using JFrame import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame( ) { Container c = getContentPane(); c.setFlowLayout( new FlowLayout() ); c.add( Name of component here ); }
main method public static void main( String args[ ] ) { MyFrame test = new MyFrame( ); test.setSize( length, width ); test.show( ); }
Inner Class for event handling private class ActionEventHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { if ( e.getSource( ) == exitButton ) System.exit(0); else if ( e.getSource( ) == something else ) { do something else } }}
Listening for actions public class MyFrame extends JFrame { public MyFrame( ) { public MyFrame( ) { Container c = getContentPane(); Container c = getContentPane(); c.setFlowLayout( new FlowLayout() ); c.setFlowLayout( new FlowLayout() ); ActionEventHandler handler = new ActionEventHandler( ); ActionEventHandler handler = new ActionEventHandler( ); JButton exitButton = new JButton( “Exit” ); JButton exitButton = new JButton( “Exit” ); exitButton.addActionListener( handler ); exitButton.addActionListener( handler ); c.add( exitButton ); c.add( exitButton );}
TimeTestWindow demo
Using NetBeans Building a GUI is much easier and quicker using a visual development environment Will illustrate this using NetBeans Example taken from Chapter 8 of NetBeans - The Definitive Guide by Tim Boudreau, Jesse Glick, Simeon Greene, Vaughn Spurlin & Jack Woehr, O’Reilly