Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^400) | Event-Driven Input and Output
public classCopyString
{
// Define a button handler
private static classButtonHandler implementsActionListener
{
public void actionPerformed(ActionEvent event) // Event handler method
{
outputLabel.setText(inputField.getText());
}
} // End of ButtonHandler
// Declare pieces of the user interface shared by main and CopyString
private staticJLabel outputLabel; // Label for output
private staticJTextField inputField; // Input field
public static void main(String[] args)
{ // Declare pieces of the user interface accessed only by main
JFrame dataFrame; // User interface frame
Container dataPane; // Content pane
JLabel entryLabel; // Label for input field
JButton copy; // Copy button
ButtonHandler copyAction; // Declare action handler
// Instantiate the pieces of the interface
dataFrame = new JFrame();
dataPane = dataFrame.getContentPane();
dataFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dataFrame.setSize(450, 75);
dataPane.setLayout(new GridLayout(2,2));
entryLabel = new JLabel("Enter a string:");
outputLabel = new JLabel("");
inputField = new JTextField("", 30);
copy = new JButton("Copy");
copyAction = new ButtonHandler(); // Instantiate listener
copy.addActionListener(copyAction); // Register listener
// Put pieces into frame and make it visible
dataPane.add(entryLabel);
dataPane.add(inputField);
dataPane.add(copy);
dataPane.add(outputLabel);
dataFrame.setVisible(true);
}
}
The application initially displays a frame that looks like this:
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf