go to previous page   go to home page   go to next page

Answer:

Of course.


Testing GUI Input

Square Root GUI

Here is a GUI version of the square root program. The important thing here is how using a fairly simple regular expression greatly increases user friendlyness. The program is made much more tolerant of user errors.

The relevant part uses goodNumber() much as did the command line application. numberText refers to the first text field, where the enters the number. That string is retrieved from the field and tested to see if it is a positive integer. If not, an error message is sent to the result text field.


 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;
 
class SqrtPanel extends JPanel implements ActionListener 
{
  JTextField numberText;
  JTextField resultText;

  private boolean goodNumber(String user) 
  {
    return user.matches(" *[0-9]+ *");
  }
  
  public SqrtPanel()
  {
    super();
    setPreferredSize( new Dimension(300, 200) );
   
    JPanel p1 = new JPanel();
    p1.add( new JLabel("Integer") );
    numberText = new JTextField( 15 );
    p1.add(numberText);

    JPanel p2 = new JPanel();
    p2.add( new JLabel("Result") );
    resultText=new JTextField( " ", 15);
    p2.add(resultText);

    JPanel p3 = new JPanel();
    JButton calcBt = new JButton("Square Root");
    calcBt.addActionListener(this);
    calcBt.setSize(10,10);
    p3.setLayout( new FlowLayout() );
    p3.add( calcBt );

    add( new JLabel("Square Root Calculator") );
    add(p1);
    add(p2);
    add(p3);
  }

  public void actionPerformed( ActionEvent evt )  
  {
    String user = numberText.getText();     
    if ( goodNumber( user) )
    {
      int value = Integer.parseInt( user.trim() );
      resultText.setText( "" + Math.sqrt( (double)value ) );
    }
    else
      resultText.setText( "Positive integers only" );     
  }
  
}

public class SqrtCalculator
{
   public static void main ( String[] args )
   {
      JFrame frame = new JFrame( "Square Roots" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      frame.getContentPane().add( new SqrtPanel() ); 
      frame.pack();
      frame.setVisible( true );
   }
}


QUESTION 9:

(Java Review: ) Can you construct a String that contains a quote mark? Will the following work?

String test = "Quoth the raven, "Nevermore."";