// SwapTextGUI.java
// GUI which swaps contents of two text fields
// when user presses ENTER in console.
//
// Uses ConsoleInput.java
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* Window with two uneditable text fields
* whose contents are swapped when user
* presses ENTER in console.
*
* @author D. Nixon
*/
public class SwapTextGUI extends JFrame
{
private JTextField topField;
private JTextField bottomField;
private final static String lineBreak
= System.getProperty("line.separator");
/**
* Creates this window.
*/
public SwapTextGUI()
{
// Size of this window in pixels:
setSize(350, 200);
// Set this window's distance from
// left and top of screen:
setLocation(100, 100);
// Set title bar:
setTitle("Swapping texts");
// Prepare to add text fields and panel:
Container contentPane = getContentPane();
// Create and add text field at top:
topField = new JTextField();
topField.setEditable(false);
topField.setText("Starting on top, ending on bottom.");
contentPane.add(topField, BorderLayout.NORTH);
// Create and add text field at bottom:
bottomField = new JTextField();
bottomField.setEditable(false);
bottomField.setText("Starting on bottom, ending on top.");
contentPane.add(bottomField, BorderLayout.SOUTH);
// Create and add text area at center,
// containing instructions to user:
JTextArea area = new JTextArea();
area.setEditable(false);
area.setText(lineBreak);
area.append("Press ENTER in console to swap text");
area.append(lineBreak);
area.append("in top and bottom text fields.");
contentPane.add(area, BorderLayout.CENTER);
// Enable program to quit when window closes:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make window appear on screen:
setVisible(true);
} // constructor
/**
* Prompts user, in console, to press ENTER.
* Then swaps contents of top and bottom text fields.
*/
public void interactWithConsole()
{
System.out.println();
System.out.println("Press ENTER here in console to "
+ "swap contents of text fields ...");
ConsoleInput.readLine();
swapText(topField, bottomField);
} // method interactWithConsole()
/**
* Main method
*
* @param args command-line arguments - none needed
*/
public static void main(String[] args)
{
SwapTextGUI window = new SwapTextGUI();
window.interactWithConsole();
} // method main
/**
* Swaps the strings contained in the two
* specified text fields.
*
* @param field1 - a text field
* @param field2 - a text field
*/
public static void swapText(JTextField field1,
JTextField field2)
{
String temp = field1.getText();
field1.setText(field2.getText());
field2.setText(temp);
} // swapText
} // class SwapTextGUI