import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyLayoutExample { public static void main(String[] args) { new MyFrame().show(); } } class MyFrame extends JFrame implements ActionListener { JButton submitButton, resetButton; JTextField nameField, emailField; /** Constructs a new frame and its contents. */ public MyFrame() { super(); setTitle("My Frame"); setDefaultCloseOperation(EXIT_ON_CLOSE); // the "content pane" is the main panel in which I'll put everything JPanel contentPane = new JPanel(new BorderLayout()); // set up a panel to hold some labels and text fields, in the center JPanel centerPanel = new JPanel(); // use dummy interior panels to hold each grid column JPanel p1 = new JPanel(new GridLayout(0, 1)); p1.add(new JLabel("Name: ")); p1.add(new JLabel("Email address: ")); centerPanel.add(p1); JPanel p2 = new JPanel(new GridLayout(0, 1)); nameField = new JTextField(16); emailField = new JTextField(16); p2.add(nameField); p2.add(emailField); centerPanel.add(p2); contentPane.add(centerPanel, BorderLayout.CENTER); // set up a panel to hold a few buttons, centered, in the south JPanel southButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); submitButton = new JButton("Submit"); submitButton.addActionListener(this); resetButton = new JButton("Reset"); resetButton.addActionListener(this); southButtonPanel.add(submitButton); southButtonPanel.add(resetButton); contentPane.add(southButtonPanel, BorderLayout.SOUTH); // now that I've done my layout, I need to tell the frame to use // my content pane! setContentPane(contentPane); pack(); // shrink my frame so that it is just exactly big enough. setResizable(false); } /** Processes action events from components contained in this frame. */ public void actionPerformed(ActionEvent event) { String nameText = nameField.getText(); String emailText = emailField.getText(); Object source = event.getSource(); if (source == submitButton) // pop up a quickie message box with this frame as its parent, // and with the message I specify JOptionPane.showMessageDialog(this, "Name entered : " + nameText + "\n" + "Email entered: " + emailText); else if (source == resetButton) { // wipe the text fields clean nameField.setText(""); emailField.setText(""); } } }