As a beginner Java programmer I would like some help as to understanding the best way or technique for building a swing UI for my console app.
The console app works well now I would like to convert it to a swing app. I would like to have a swing JTextArea in a JScrollPane that the user can edit to input their string then click a countwords button and get an output as a int.
The code for my console app and my attempt to the swing app as well is below. I have spent quite a bit of time trying to research this but I can't seem to get it right.
My console app :
import java.util.*;
public class WordCounter{
public static void main(String args[])
{
// Create Scanner object
Scanner s=new Scanner(System.in);
// Read a string
String st=s.nextLine();
//Split string with space
String words[]=st.trim().split(" ");
System.out.println("No. of words "+words.length);
}
}
My attempt at Swing :
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JTextArea;
import java.util.*;
class Countswords extends JPanel {
public Countswords() {
myTextArea();
}
private void myTextArea() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 200));
JTextArea textArea = new JTextArea(5, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
// textArea.setEditable(true);
JTextArea.setText(userInput);
}
public static void showFrame() {
JPanel panel = new Countswords();
panel.setOpaque(true);
JFrame frame = new JFrame("My Text Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
// Create Scanner object
// Scanner s=new Scanner(System.in);
// Read a string
// String st=s.nextLine();
// Split string with space
// String words[]=st.trim().split(" ");
// System.out.println("No. of words "+words.length);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Countswords.showFrame();
}
});
}
}