import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Basic GUI example that demonstrates multiple layouts with JPanels * This class has no event handling. Therefore, if you close this Frame * the program will still run. */ public class SimpleGUI extends JFrame { public SimpleGUI() { super( "Simple GUI Example" ); // Sets the application icon setIconImage(Toolkit.getDefaultToolkit().getImage("w:/cis226/lectures/J2-GUI-Event/event/ex4/duke_wave.gif")); final JFrame parent = this; JPanel mainPanel = new JPanel(); JPanel userPanel = new JPanel(); // username panel JPanel passPanel = new JPanel(); // password panel JPanel buttonPanel = new JPanel(); // button panel final JTextField userTxtFld = new JTextField( 30 ); final JPasswordField passFld = new JPasswordField( 30 ); // NOTICE -- Swing labels can parse and interpret html code JLabel userLbl = new JLabel( "Username:" ); JLabel passLbl = new JLabel( "Password:" ); JButton okBtn = new JButton( "OK" ); JButton cancelBtn = new JButton( "CANCEL" ); userPanel.add( userLbl ); userPanel.add( userTxtFld ); passPanel.add( passLbl ); passPanel.add( passFld ); buttonPanel.add( okBtn ); buttonPanel.add( cancelBtn ); // We use a gridlayout to set the components mainPanel.setLayout( new GridLayout( 3, 1 ) ); mainPanel.add( userPanel ); mainPanel.add( passPanel ); mainPanel.add( buttonPanel ); getContentPane().add( mainPanel ); // all components for JFrame, JWindow, and JDialog // are added to container called the ContentPane.1 /** * With the help of inner anonymous classes, I can condense the previous code into one file * HERE WE USE AN ADAPTOR CLASS, THIS ELIMINATES THE NEED TO DEFINE */ addWindowListener( new WindowAdapter () { public void windowClosing(WindowEvent e) { System.exit( 0 ); // terminate the program } }); okBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { String password = new String( passFld.getPassword() ); JOptionPane.showMessageDialog(parent, "You have entered " + userTxtFld.getText() + " as your username and " + password + " as your password.", "OK Message", JOptionPane.INFORMATION_MESSAGE ); } }); cancelBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { JOptionPane.showMessageDialog(parent, "Login Cancelled", "CANCEL Message", JOptionPane.ERROR_MESSAGE ); } }); setSize( 500, 500 ); pack(); // set all components to their preferred size } public static void main( String[] args ) { SimpleGUI gui = new SimpleGUI(); gui.setVisible( true ); } }