write a program in Java that computes the number of words in a text entered in a
ID: 3759247 • Letter: W
Question
write a program in Java that computes the number of words in a text entered in a text field. Use the following graphical objects:
• a text field for the input text (one line of text)
• labels to output the word count
• a button that, when pressed, computes the word count
• a button that, when pressed, clears the text field
• a panel, that includes all graphical objects listed above
Make your application run in a window (JFrame) and use a proper layout, backgrounds and colors to make all objects clearly visible.
Extra credit (maximum 2 points) will be given for additional text statistics (for example, maximum, minimum and average word size, number of numeric tokens.
Explanation / Answer
import java.awt.*; // Using AWT containers and components
import javax.swing.*;
import java.awt.event.*; // Using AWT events and listener interfaces
public class AWTCounter extends Frame implements ActionListener
{
private JLabel lblCount; // declare component Label
private JTextField tfCount; // declare component TextField
private JButton btnCount; // declare component Button
private int count = 0; // counter's value
public AWTCounter ()
{
setLayout(new FlowLayout());
lblCount = new JLabel("Counter"); // allocate Label instance
add(lblCount); // "this" Frame adds Label
tfCount = new JTextField(count + "", 10); // allocate
tfCount.setEditable(false); // read-only
add(tfCount); // "this" Frame adds tfCount
btnCount = new Button("Count"); // allocate Button instance
add(btnCount); // "this" Frame adds btnCount
btnCount.addActionListener(this);
setSize(250, 100); // "this" Frame sets initial size
setTitle("AWT Counter"); // "this" Frame sets title
setVisible(true); // show "this" Frame
}
@Override
public void actionPerformed(ActionEvent evt)
{
++count; // incrase the counter value
tfCount.setText(count + ""); // display on the TextField
// setText() takes a String
}
public static void main(String[] args)
{
new AWTCounter();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.