I have been given an assignment whereby I need to create a tool that analyses a field of text and then outputs a couple of statistics about said body of text via a button click. I seem to have most of the basic framework up but am struggling with getting my two labels that are averageLength and totalWords inside my JPanel and also on getting said JPanel below where I enter my body of text. Any help would be much appreciated. Code is here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextStatisticsPanel extends JPanel
{
//Field for block of text
private JTextArea userText;
//Button to calculate Statistics
private JButton stats;
//Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
public TextStatisticsPanel(){
//creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
//create button
stats = new JButton("Update Text Statistics");
//Listener for button
stats.addActionListener(new ButtonListener());
//Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
//Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension (350, 400));
scroller.setBorder(BorderFactory.createTitledBorder ("Enter the text below"));
//Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
totalWords = new JLabel("The total number of words: ");
//add GUI
add(statPanel);
add(scroller);
add(averageLength);
add(totalWords);
setBackground(new java.awt.Color(202, 225, 255));
setPreferredSize(new Dimension (400, 600));
add(stats);
}
// When button is pressed do :
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == stats){
//Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate()
{
//Grab text user inputed
String text = userText.getText();
//Split the text by each space to find the number of words
String[] words = text.split(" ");
//Calculation for average
float average = (text.length() - words.length)/words.length;
//
averageLength.setText(String.valueOf(average));
totalWords.setText(String.valueOf(words.length));
System.out.println(averageLength);
System.out.println(totalWords);
}
}
}
OK so as to try and use MCVE, this is part of the relevent code however I am still unable to work out the root of the problem.
The code for my second panel is :
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
SO as per my understanding this is me creating a second panel among my app. The problem however is that this is being placed in a seemingly random location and is not wrapping around the two labels I wish to be inside this panel and I am unsure how to fix this problem.
The main class code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JFrame;
public class TextStatistics {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatisticsPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Providing a visual example to show the code I believe is the problem and the problem I am encountering
Here's the GUI I put together.
These are the major changes I made.
I put the JFrame code in a Runnable, so I could start the Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method ensures that the Swing components are created and updated on the Event Dispatch thread. Oracle and I require that everyone starts their Swing applications on the Event Dispatch thread.
I defined several new JPanels in your TextStatisticsPanel class and used two Swing layout managers, BorderLayout and BoxLayout. Study the link in the previous sentence. By study, I mean spend at least two to three weeks of 8 hour days absorbing all of the ins and outs of the Swing layout managers.
I added JTextFields to hold the calculated values. That's what JTextFields are for.
I fixed the integer division in your statUpdate method.
Here's the code. I put everything together in one file so it would be easier to upload. You should put the classes in separate files.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TextStatistics {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatistics().new TextStatisticsPanel();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public class TextStatisticsPanel extends JPanel {
private static final long serialVersionUID = 9049744714586970558L;
// Field for block of text
private JTextArea userText;
// Button to calculate Statistics
private JButton stats;
// Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
private JTextField averageLengthField, totalWordsField;
public TextStatisticsPanel() {
// creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
// create button
stats = new JButton("Update Text Statistics");
stats.setAlignmentX(JButton.CENTER_ALIGNMENT);
// Listener for button
stats.addActionListener(new ButtonListener());
// Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory
.createTitledBorder("Text Statistics"));
statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.PAGE_AXIS));
statPanel.setOpaque(false);
// Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension(350, 400));
scroller.setBorder(BorderFactory
.createTitledBorder("Enter the text below"));
// Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
averageLength.setOpaque(false);
averageLengthField = new JTextField(10);
averageLengthField.setEditable(false);
averageLengthField.setOpaque(false);
totalWords = new JLabel("The total number of words: ");
totalWords.setOpaque(false);
totalWordsField = new JTextField(10);
totalWordsField.setEditable(false);
totalWordsField.setOpaque(false);
// add GUI
setLayout(new BorderLayout());
statPanel.add(stats);
statPanel.add(Box.createVerticalStrut(10));
JPanel lengthPanel = new JPanel();
lengthPanel.setOpaque(false);
lengthPanel.add(averageLength);
lengthPanel.add(averageLengthField);
statPanel.add(lengthPanel);
statPanel.add(Box.createVerticalStrut(10));
JPanel wordsPanel = new JPanel();
wordsPanel.setOpaque(false);
wordsPanel.add(totalWords);
wordsPanel.add(totalWordsField);
statPanel.add(wordsPanel);
add(statPanel, BorderLayout.SOUTH);
add(scroller, BorderLayout.CENTER);
setBackground(new java.awt.Color(202, 225, 255));
}
// When button is pressed do :
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == stats) {
// Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate() {
// Grab text user inputed
String text = userText.getText();
// Split the text by each space to find the number of words
String[] words = text.split(" ");
// Calculation for average
float average = ((float) text.length() - words.length)
/ words.length;
//
averageLengthField.setText(String.valueOf(average));
totalWordsField.setText(String.valueOf(words.length));
}
}
}
}