Listing 11.1 JTextField Components and a Clear Button (TJTextField.java) // Demonstrates Swing text fields. /* * * */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TJTextField extends JApplet { Container container; JTextField textField1, textField2; public void init() { // 1. Get the handle on the applet's content pane. container = this.getContentPane(); // 2. Prepare the applet with vertical box layout. container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); // 3. Create two text-fields and a button. textField1 = new JTextField( "Enter some text here and press return", // Initial string 20); // 20 columns width // Add an action listener to this text field. textField1.addActionListener(new TextFieldListener()); // Assign a line border with black color. textField1.setBorder(BorderFactory.createLineBorder(Color.black)); textField2 = new JTextField(20); // 20 columns width. // Assign a line border with blue color. textField2.setBorder(BorderFactory.createLineBorder(Color.blue)); JButton button = new JButton("Clear"); // Add an action listener to this button. button.addActionListener(new ButtonListener()); // 4. Add text-fields and button to the applet's content pane. container.add(Box.createVerticalGlue()); //Add a glue component. container.add(textField1); // Add the textfield1. container.add(Box.createVerticalGlue()); // Add another glue component. container.add(textField2); // add the textfield2 container.add(Box.createVerticalGlue()); // Add another glue component. container.add(button); // Add the button. } // 5. The text field listener class. class TextFieldListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Retrieve the text entered in textfield1 // and assign it the other textfield. textField2.setText(e.getActionCommand()); } } // 6. The button listener class. class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Clear both the text fields. textField1.setText(""); textField1.requestFocus(); // Get the focus back textField2.setText(""); } } } Listing 11.2 JPasswordField and JTextField components (TJPasswordField.java) // Demonstrates Swing password fields. /* * * */ import javax.swing.*; import java.awt.*; public class TJPasswordField extends JApplet { Container container; public void init() { // 1. Get the handle on the applet's content pane. container = this.getContentPane(); // 2. Set the applet background color and layout. container.setBackground(Color.lightGray); GridBagLayout gridbag = new GridBagLayout(); container.setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(5,5,5,5); // top, left, bottom, right c.weightx = 1; c.weighty = 1; // 3. Create the component objects // and add them to the applet using grid bag layout. c.fill = c.BOTH; c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; JLabel label1 = new JLabel("Enter the Username: "); gridbag.setConstraints(label1, c); container.add(label1); c.gridx = 0; c.gridy = 1; JLabel label2 = new JLabel("Enter the Pass-Word: "); gridbag.setConstraints(label2, c); container.add(label2); c.fill = c.NONE; c.anchor = c.WEST; c.gridx = 1; c.gridy = 0; JTextField textField = new JTextField("satyaraj", 15); gridbag.setConstraints(textField, c); container.add(textField); c.gridx = 1; c.gridy = 1; JPasswordField passwordField = new JPasswordField(6); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); gridbag.setConstraints(passwordField, c); container.add(passwordField); // 4. Set an echo character for the password field. // Note: The default character is "*". passwordField.setEchoChar('x'); } } Listing 11.3 JTextArea and Edit Buttons (TJTextArea.java) // Demonstrates the Swing text area. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TJTextArea extends JFrame { // 1. Declare the references for the following objects. Container container; JLabel label = null; JTextField textField = null; JTextArea textArea = null; JButton insertButton = null; JButton deleteButton = null; JButton cutButton = null; JButton copyButton = null; JButton pasteButton = null; public TJTextArea() { // 2. Assign a name to the frame and obtain a handle // on the frame's content pane. super("TJTextArea"); container = this.getContentPane(); // 3. Create the fonts for label and text area. Font labelFont = new Font("SanSerif", Font.BOLD, 14); Font textFont = new Font("Dialog", Font.PLAIN, 12); // 4. Use the gridbag layout for the applet. GridBagLayout gridbag = new GridBagLayout(); container.setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); // 5. Add a label. c.fill = c.BOTH; c.insets = new Insets(2,2,2,2); c.gridx = 0; c.gridy = 0; c.gridwidth = 5; c.gridheight = 1; c.anchor = c.WEST; c.weightx = 1.0; c.weighty = 1.0; label = new JLabel("Enter Text: "); label.setFont(labelFont); gridbag.setConstraints(label, c); container.add(label); // add the label // 6. Add a text field. c.anchor = c.CENTER; c.gridx = 0; c.gridy = 1; textField = new JTextField(); gridbag.setConstraints(textField, c); container.add(textField); // add the text-field // 7. Add the Insert button. c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight = 1; c.fill = c.BOTH; insertButton = new JButton("Insert"); insertButton.setBackground(Color.lightGray); gridbag.setConstraints(insertButton, c); container.add(insertButton); // add insert button ButtonListener inButtonListener = new ButtonListener(); insertButton.addActionListener(inButtonListener); // 8. Add the Delete button. c.gridx = 1; c.gridy = 2; deleteButton = new JButton("Delete"); deleteButton.setBackground(Color.lightGray); gridbag.setConstraints(deleteButton, c); container.add(deleteButton); // add the delete button ButtonListener dlButtonListener = new ButtonListener(); deleteButton.addActionListener(dlButtonListener); // 9. Add the Cut button. c.gridx = 2; c.gridy = 2; cutButton = new JButton("Cut"); cutButton.setBackground(Color.lightGray); gridbag.setConstraints(cutButton, c); container.add(cutButton); // add the cut button ButtonListener ctButtonListener = new ButtonListener(); cutButton.addActionListener(ctButtonListener); // 10. Add the Copy button. c.gridx = 3; c.gridy = 2; copyButton = new JButton("Copy"); copyButton.setBackground(Color.lightGray); gridbag.setConstraints(copyButton, c); container.add(copyButton); // add the copy button ButtonListener cpButtonListener = new ButtonListener(); copyButton.addActionListener(cpButtonListener); // 11. Add the Paste button. c.gridx = 4; c.gridy = 2; pasteButton = new JButton("Paste"); pasteButton.setBackground(Color.lightGray); gridbag.setConstraints(pasteButton, c); container.add(pasteButton); // add the paste button ButtonListener psButtonListener = new ButtonListener(); pasteButton.addActionListener(psButtonListener); // 12. Add the text area. c.gridx = 0; c.gridy = 3; c.gridwidth = 5; c.gridheight = 1; c.weightx = 1.0; c.weighty = 1.0; c.anchor = c.CENTER; c.fill = c.BOTH; String someText = "The Swing 'JTextArea' is a " + "light-weight component."; textArea = new JTextArea(someText, // To be displayed initially 6, // Number of rows. 30); // Number of columns. textArea.setFont(textFont); textArea.setBackground(Color.white); textArea.setSelectionColor(Color.yellow); textArea.setTabSize(5); // The tab size. textArea.setLineWrap(true); // Wrap the line at the container end. gridbag.setConstraints(textArea, c); container.add(textArea); // Add the text area. // 13. Add the window listener to close the frame // and display it with the specified size. addWindowListener(new WindowEventHandler()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setSize(400, 200); // width=400, height=200 show(); // Display the frame. } // 14. Button listener class. class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); if (b == insertButton) { try { // Insert text at the caret position. The text is // is retrieved from the text field by using getText(). textArea.insert(textField.getText(), textArea.getCaretPosition()); } catch (IllegalArgumentException excep) { } } else if (b == deleteButton) { textArea.replaceSelection(""); // Selected text is deleted. } else if (b == cutButton) { textArea.cut(); // Cut operation. } else if (b == copyButton) { textArea.copy(); // Copy operation. } else if (b == pasteButton) { textArea.paste(); // Paste operation. } } } // 15. The listener class to handle closing of the frame. class WindowEventHandler extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); } } // 16. The main method. public static void main(String[] args){ new TJTextArea(); } } Listing 11.4 JEditorPane Displaying a Web Page (TJEditorPane.java) // Demonstrates the Swing editor pane. import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.net.*; public class TJEditorPane extends JFrame { JTextField textField; JEditorPane editorPane; public TJEditorPane () { // 1. Assign a title to the frame and obtain // a reference to the frame's content pane. super("TJEditorPane"); Container container = this.getContentPane(); // 2. Create a label and attach it to a panel. JLabel label = new JLabel("Enter a URL: "); JPanel panel = new JPanel(new GridLayout(2,1)); panel.add(label); // 3. Create a text field and add it to the panel. textField = new JTextField(); textField.addActionListener(new TextFieldListener()); panel.add(textField); // 4. Add the panel to the content pane. container.add(panel, BorderLayout.NORTH); // 5. Create an editor pane and add it to the content pane // through a scroll pane. editorPane = new JEditorPane(); JScrollPane scrollPane = new JScrollPane(editorPane); container.add(scrollPane); // 6. Add the window listener to close the frame // and display it with the specified size. addWindowListener(new WindowEventHandler()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setSize(350, 200); // width=350, height=200 setBackground(Color.lightGray); setForeground(Color.black); show(); // Display the frame // 7. Get the focus to textField. textField.requestFocus(); } // 8. The text field listener class. class TextFieldListener implements ActionListener { public void actionPerformed(ActionEvent ae) { URL pageURL = null; // 9. Create the URL object for the text that has been // entered in the text field. try { pageURL = new URL(textField.getText()); } catch (MalformedURLException me) { System.out.println("MalformedURL"); } // 10. Assign the page to the editor pane so that the // page is displayed. try { editorPane.setPage(pageURL); } catch (java.io.IOException ioe) { System.out.println("IOException while loading page"); } } } // 11. The main method. public static void main(String[] args) { new TJEditorPane(); } // 12. The listener class to handle closing of the frame. class WindowEventHandler extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); } } } Listing 11.5 JTextPane Displaying Styled Text (TJTextPane.java) // TJTextPane.java/* * * */ import javax.swing.*; import javax.swing.text.*; import java.awt.*; public class TJTextPane extends JApplet { JTextPane textPane = null; MutableAttributeSet centerAlign; MutableAttributeSet charStyle1, charStyle2, charStyle3; public void init() { // 1. Create a text pane object. textPane = new JTextPane(); // 2. Prepare the paragraph attribute for center alignment. centerAlign = new SimpleAttributeSet(); StyleConstants.setAlignment(centerAlign, StyleConstants.ALIGN_CENTER); // 3. Prepare the character attribute set called style1. charStyle1 = new SimpleAttributeSet(); StyleConstants.setFontFamily(charStyle1, "Serif"); StyleConstants.setFontSize(charStyle1, 75); // 4. Prepare another character attribute set called style2. charStyle2 = new SimpleAttributeSet(); StyleConstants.setFontSize(charStyle2, 35); StyleConstants.setUnderline(charStyle2, true); StyleConstants.setForeground(charStyle2, Color.red); StyleConstants.setBold(charStyle2, true); StyleConstants.setItalic(charStyle2, true); // 5. Prepare one more character attribute set called style3. charStyle3 = new SimpleAttributeSet(); StyleConstants.setFontSize(charStyle3, 20); // 6. Get a reference to the content model of the text pane. Document contentModel = textPane.getDocument(); try { // 7. Assign a position to the caret. textPane.setCaretPosition(contentModel.getLength()); // Insert the Java Duke icon. textPane.insertIcon(new ImageIcon("javaIcon1.gif")); // 8. Assign character attributes to the text pane. textPane.setCharacterAttributes(charStyle1, false); // Assign paragraph attributes to the text pane textPane.setParagraphAttributes(centerAlign, true); String javaText = "Java\n"; // 9. Insert the string in the content of text pane. contentModel.insertString(contentModel.getLength(), javaText, charStyle1); // 10. Assign new character attributes to the text pane. textPane.setCharacterAttributes(charStyle2, true); String coolText = "JFC Swing is Cool!\n"; // 11. Insert the string in the content of text pane. contentModel.insertString(contentModel.getLength(), coolText, charStyle2); // 12. Assign new character attributes to the text pane. textPane.setCharacterAttributes(charStyle3, true); String doneText = "Done!"; // 13. Insert the string in the content of text pane. contentModel.insertString(contentModel.getLength(), doneText, charStyle3); } catch(BadLocationException blexcep) { System.err.println("Exception while inserting the string."); blexcep.printStackTrace(); } // 14. Add the text pane to a scroll pane. JScrollPane scrollPane = new JScrollPane(textPane); // 15. Finally, add the scroll pane to the content pane. getContentPane().add(scrollPane); } }