Academic Java    Java Tutorial  >  Applets  >  applet form

applet form Example

Java applet form EXAMPLE output This applet example shows how to implement a form in an applet. The applet presents a simple interface for the user to enter personal (email) information.

When the user selects the button at the bottom of the form, information entered on the form is output. Normally it would be sent over the Internet, the protocol for doing that is not shown here.
// Applet Form Example
import javax.swing.*; import javax.swing.text.*;
import java.awt.*; import java.awt.event.*;

class AppletFormExample extends JApplet implements ActionListener {

   String[] fieldNames = {"To:","Cc:","Subject:","Message:"};
   JComponent[] jca = new JComponent[fieldNames.length];
   int[][] fs = {{16,1},{16,1},{16,1},{16,10}};

   @Override public void init() {
      Container cp = getContentPane();
      cp.setLayout(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.anchor = GridBagConstraints.WEST;
      gbc.insets = new Insets(5,10,5,5);
      for(int i=0;i<fieldNames.length;++i) {
         gbc.gridwidth = GridBagConstraints.RELATIVE;
         cp.add(new JLabel(fieldNames[i]),gbc);
         gbc.gridwidth = GridBagConstraints.REMAINDER;
         if(fs[i][1]==1) {
            JTextField tf=new JTextField(fs[i][0]);
            jca[i]=tf; cp.add(tf,gbc);
         }
         else {
            JTextArea ta=new JTextArea(fs[i][1],fs[i][0]);
            ta.setLineWrap(true); ta.setWrapStyleWord(true);
            JScrollPane jsp = new JScrollPane(ta,
               JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
               JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            jca[i]=ta; cp.add(jsp,gbc);
         }
      }
      JButton b = new JButton("send"); b.addActionListener(this);
      gbc.anchor = GridBagConstraints.EAST; cp.add(b,gbc);
   }

   public void actionPerformed(ActionEvent evt) {
      for(int i=0;i<fieldNames.length;++i) {
         System.out.println(fieldNames[i]+" " + ((JTextComponent)jca[i]).getText());
      }
   }
}