import javax.swing.*; public class TextEditor extends JFrame { private JTextArea textArea; public TextEditor() { textArea = new JTextArea(); textArea.setText("Hello world!"); add(textArea); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true); } public static void main(String[] args) { new TextEditor(); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CountWords extends JFrame { private JTextArea textArea; private JLabel label; public CountWords() { textArea = new JTextArea(); textArea.setLineWrap(true); JScrollPane scrollPane = new JScrollPane(textArea); label = new JLabel("Words: 0"); add(scrollPane, BorderLayout.CENTER); add(label, BorderLayout.SOUTH); textArea.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { updateWordCount(); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setVisible(true); } private void updateWordCount() { String text = textArea.getText(); int wordCount = text.split("\\s+").length; label.setText("Words: " + wordCount); } public static void main(String[] args) { new CountWords(); } }This example creates a text area that automatically counts the number of words typed by the user. The setText method is used to set the initial text content of the text area. The updateWordCount method is called whenever the user types something new or deletes something from the text area, and it updates the word count displayed in a label. The code uses several classes from the javax.swing and java.awt packages.