Java Reference
In-Depth Information
1
// Fig. 12.48: TextAreaDemo.java
2
// Testing TextAreaFrame.
3
import javax.swing.JFrame;
4
5
public class TextAreaDemo
6
{
7
public static void main(String[] args)
8
{
9
TextAreaFrame textAreaFrame = new TextAreaFrame();
10
textAreaFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
textAreaFrame.setSize( 425 , 200 );
12
textAreaFrame.setVisible( true );
13
}
14
} // end class TextAreaDemo
Fig. 12.48 | Testing TextAreaFrame .
a BoxLayout layout manager (discussed in detail in Section 22.9) to arrange the GUI com-
ponents either horizontally or vertically. Box 's static method createHorizontalBox cre-
ates a Box that arranges components from left to right in the order that they're attached.
Lines 26 and 43 create JTextArea s textArea1 and textArea2 . Line 26 uses JText-
Area 's three-argument constructor, which takes a String representing the initial text and
two int s specifying that the JTextArea has 10 rows and 15 columns. Line 43 uses JText-
Area 's two-argument constructor, specifying that the JTextArea has 10 rows and 15 col-
umns. Line 26 specifies that demo should be displayed as the default JTextArea content.
A JTextArea does not provide scrollbars if it cannot display its complete contents. So, line
27 creates a JScrollPane object, initializes it with textArea1 and attaches it to container
box . By default, horizontal and vertical scrollbars appear as necessary in a JScrollPane .
Lines 29-41 create JButton object copyJButton with the label "Copy >>>" , add copy-
JButton to container box and register the event handler for copyJButton 's ActionEvent .
This button provides the external event that determines when the program should copy
the selected text in textArea1 to textArea2 . When the user clicks copyJButton , line 38
in actionPerformed indicates that method getSelectedText (inherited into JTextArea
from JTextComponent ) should return the selected text from textArea1 . The user selects
text by dragging the mouse over the desired text to highlight it. Method setText changes
the text in textArea2 to the string returned by getSelectedText .
Lines 43-45 create textArea2 , set its editable property to false and add it to con-
tainer box . Line 47 adds box to the JFrame . Recall from Section 12.18.2 that the default
layout of a JFrame is a BorderLayout and that the add method by default attaches its argu-
ment to the CENTER of the BorderLayout .
 
Search WWH ::




Custom Search