Parsing text boxes and text areas in Java graphical programming

  • 2020-04-01 04:15:49
  • OfStack

In a graphical interface, text boxes and text areas are the components used for input and output of information.
The text box

A text box (JTextField) is a box in the interface for input and output of a line of text. The JTextField class is used to create text boxes. The interface associated with the text box is the ActionListener.

The basic content of a text box handler has the following aspects:

Declare a text field name. Creates a text box object. Adds a text box object to a container. Register the monitor for the textbox object you want to control, and listen for the end of the textbox's input (that is, the enter key) event. A method to handle text box events, the completion of the interception of events and processing.

The main constructor of the JTextField class:

JTextField(), the character length of the text box is 1. JTextField(int columns), the initial value of the text box is an empty string, and the character length of the text box is set to columns. JTextField(String text), a String whose textbox starts with a value of text. JTextField (String text, int columns); The initial value of the text box is text, and the character length of the text box is columns.

Other methods of the JTextField class:

SetFont (Font f), set the Font SetText (String text), which sets the text in the text box GetText (), get the text in the text box. SetEditable (Boolean), which specifies the editable value of the text box, true by default, editable. SetHorizontalAlignment (int alignment) sets the alignment of the text. Alignment: jtextfield.left, jtextfield.center, jtextfield.right. RequestFocus (), which sets the focus. AddActionListener (ActionListener), which sets the action monitor for the text box, and specifies that the ActionListener object receives the input end action event that occurs on the text box. RemoveActionListener removes the textbox monitor. GetColumns () returns the number of columns in the text box. GetMinimumSize (), which returns the minimum size required for the text box. GetMinimumSize (int), returns the minimum size required for the text box with the specified number of characters. GetPreferredSize (), which returns the size the text box wants to have. GetPreferredSize (int), which returns the desired size of the text box for the specified number of characters.

Applet has two text boxes. One text is used to enter an integer, and the other text box displays the square value of the integer. The program USES the string to transform the primitive type method long.parselong (text1.gettext ()), reads the string in text1 and converts it to an integer. The program USES an instance of the Sqr class as the monitor, but in order for the monitor to access the variables in the main class, the variables in the main class are declared as class variables and access is not set (see the source file).

A password box (JPasswordField) is a single-line input component, much like a JTextField. Password box more than a masking function, is in the input, will be a specified character (generally * character) output. In addition to the text box methods described above, there are some other methods commonly used for password boxes:

GetEchoChar (), returns the echo character of the password. SetEchoChar (char), sets the echo character of the password box.

Text area

A text area (JTextArea) is an area on a form where text is placed. The main difference between a text area and a text box is that the text area can hold multiple lines of text. The JTextArea class in the javax.swing package is used to create text areas. The JTextArea component has no events.

The basic content of a text area handler has the following aspects:

Declare a text field name. Creates a text area object. Adds a text area object to a container.

The main construction method of JTextArea class:

JTextArea(), creates a text area object with the default number of columns and rows. JTextArea(String s), with s as the initial value, creates a text area object. JTextArea(Strings,int x,int y), with s as the initial value, the number of rows is x, the number of columns is y, create a text area object. JTextArea(int x,int y) creates a text area object with the number of rows as x and the number of columns as y.

Other common methods of the JTextArea class:

SetText (String s), set to display the text while clearing the original text. GetText (), gets the text in the text area. Insert (String s,int x) to insert the specified text at the specified location. Replace (String s,int x,int y), replace the text from the x position to the y position with the given one. Append (String s), appends text to the text area. GetCarePosition (), gets the position of the active cursor in the text area. SetCarePosition (int n), which sets the position of the active cursor. SetLineWrap (Boolean b), set to wrap, by default, not wrap.

The following code creates a text area and sets it to wrap automatically.


  JTextArea textA = new JTextArea( "I am a text area" ,10,15);
  textA.setLineWrap(true);// Set line wrap 


When there is too much content in the text area to display all the text area, the text area can be equipped with a scroll bar. The following code can be used to set the scroll bar for the text area:


  JTextArea ta = new JTextArea();
  JScrollPane jsp = new JScrollPane(ta);// Add a scroll bar to the text area 

In a GUI, text boxes and text areas are often used to implement the input and output of data. If text field input is used, an additional data entry completion button is usually set. When the data entry is finished, click this button. The event handler USES the getText() method to read the string information from the text area. In the case of a text box, a carriage return at the end of the input can fire the input completion event, usually without a separate button. The event handler can use the word analyzer to analyze a number, and then use the string conversion method to get the input value. For the output, the program converts the value to a string and then outputs the data to a text box or text area through the setText() method.

Applet sets up a text area, a text box, and two buttons. The user enters the sequence of integers in the text area, clicks the sum button, the program sums the sequence of integers in the text area, and outputs the sum in the text box. Click the second button to clear the text area and the text box.


import java.util.*;import java.applet.*;import java.awt.*;
import javax.swing.*;import java.awt.event.*;
public class J509 extends Applet implements ActionListener{
  JTextArea textA;JTextField textF;JButton b1,b2;
  public void init(){
    setSize(250,150);
    textA=new JTextArea("",5,10);
    textA.setBackground(Color.cyan);
    textF=new JTextField("",10);
    textF.setBackground(Color.pink);
    b1=new JButton(" o   and "); b2=new JButton(" Start all over again ");
    textF.setEditable(false);
    b1.addActionListener(this); b2.addActionListener(this);
    add(textA); add(textF); add(b1);add(b2);
  }
  public void actionPerformed(ActionEvent e){
    if(e.getSource()==b1){
      String s=textA.getText();
      StringTokenizer tokens=new StringTokenizer(s);
      //Use the default set of delimiters: space, line feed, Tab line return as delimiter
      int n=tokens.countTokens(),sum=0,i;
      for(i=0;i<=n-1;i++){
        String temp=tokens.nextToken();//Take the next data from the text area
        sum+=Integer.parseInt(temp);
      } 
      textF.setText(""+sum);
    }
    else if(e.getSource()==b2){
      textA.setText(null);
      textF.setText(null);
    }
  }
}

Applet computes all Numbers that are multiples of factors from the starting integer to the ending integer. The applet container USES the GridLayout layout to divide the interface into 3 rows and columns, the first row is the label, the second and third rows are the two panels. Design two Panel container classes, Panel1 and Panel2, and divide them by GridLayout layout. Panel1 has 1 row and 6 columns, and Panel2 has 1 row and 4 columns. Then add the label and container classes Panel1 and Panel2 to the corresponding location in the window.


import java.applet.*;import javax.swing.*;
import java.awt.*;import java.awt.event.*;
class Panel1 extends JPanel{
  JTextField text1,text2,text3;
  Panel1(){//Constructor. When a Panel object is created, the Panel is initialized to have three labels
    //Three text boxes, GridLayout(1,6)
    text1=new JTextField(10);text2=new JTextField(10);
    text3=new JTextField(10);setLayout(new GridLayout(1,6));
    add(new JLabel(" Starting number ",JLabel.RIGHT));add(text1);
    add(new JLabel(" Termination of the number of ",JLabel.RIGHT));add(text2);
    add(new JLabel(" factor ",JLabel.RIGHT));add(text3);
  }
}
class Panel2 extends JPanel{//Extend the Panel class
  JTextArea text;JButton Button;
  Panel2(){//Constructor. When a Panel object is created, the Panel is initialized to have a label
    //A text box, GridLayout(1,4)
    text=new JTextArea(4,10);text.setLineWrap(true);
    JScrollPane jsp=new JScrollPane(text);
    Button=new JButton(" Start counting ");
    setLayout(new GridLayout(1,4));
    add(new JLabel(" Calculation results: ",JLabel.RIGHT));
    add(jsp);
    add(new Label());add(Button);
  }
}
public class J510 extends Applet implements ActionListener{
  Panel1 panel1;Panel2 panel2;
  public void init(){
    setLayout(new GridLayout(3,1));
    setSize(400,200);panel1=new Panel1();panel2=new Panel2();
    add(new JLabel(" Calculate the number that is a factor multiple from the beginning to the end ",JLabel.CENTER));
    add(panel1);add(panel2);
    (panel2.Button).addActionListener(this);
  }
  public void actionPerformed(ActionEvent e){
    if(e.getSource()==(panel2.Button)){
      long n1,n2,f,count=0;
      n1=Long.parseLong(panel1.text1.getText());
      n2=Long.parseLong(panel1.text2.getText());
      f=Long.parseLong(panel1.text3.getText());
      for(long i=n1;i<=n2;i++){
        if(i%f==0)
        panel2.text.append(String.valueOf(i)+"");
      }
    }
  }
}


Related articles: