calculating average of values in column of an array? - java
Ok, so I recently asked about how to get access to individual columns of an array in java, and I got an answer that worked perfectly. I then however intended to calculate things such as the maximum value in this column, and the average. However, I came across an issue. In order to access each value, I assume this column needs to be treated as an array also. However, the way I got access to each column was by storing it into a double. Therefore, I have no idea how to take each column and calculate things. Can anyone help me please? I'm sorry for posting so much that probably seems like nothing here, but we had no teacher for 12 weeks and are expected to turn in this work by just teaching ourselves, and I'm just really stuck.
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
double c4, c5, c6;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
Also, after this, I tried an alterantive code, where instead of getting individual columns, I would instead store the unwanted columns into an array so they are voided during calculation, but this also does not work. I'll admit very much that I didn't fully understand this method, but it was based on an example code that was given to us without any explanation of what it was doing, so I thought I'd atleast try. It displays the file on the text area, but gives a null pointer exception when I tried to click the max button. http://gyazo.com/27ef7cf9f4bc0c72ecdc3c1f84e6d0f8 Again, appriciate any help. I'm trying to rush a bit cuz my class is coming to me for help cuz last year, I watched a series on java basics in my free time and so had no trouble with our first year work, and they came to me for help. However, I have found no java series or anything on stuff like this, just like specific videos that only help a little. So yeah, really big thanks for any help. :)
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame.
private JPanel contentPane; //Create a container for the GUI.
//Create other components used in the GUI
private JTextField maxTxtVCC;
private JTextField maxTxtTemp;
private JTextField maxTxtLight;
private JTextField minTxtLight;
private JTextField avTxtLight;
private JTextField minTxtTemp;
private JTextField avTxtTemp;
private JTextField minTxtVCC;
private JTextField avTxtVCC;
private JButton btnMax;
private JButton btnMin;
private JButton btnAv;
private JTextField opnTxt;
private JButton btnOpn;
private TextArea textArea;
private JFileChooser fc;
private String content = "";
String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
int totalValues; //Used to hold the amount of values in the array (52790 ish)
Double[][] values;
/**
* Launch the application.
*/
public static void main(String[] args) { //Main method
EventQueue.invokeLater(new Runnable() {
public void run() { //Create a runnable method
try {
CSVFiles frame = new CSVFiles(); //Launch the GUI
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace(); //Print errors
}
}
});
}
/**
* Create the frame.
*/
public CSVFiles() { //Open constructor
super ("CSV Files"); //Create a title for the GUI
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
setBounds(100, 100, 800, 600); //Set size and location
contentPane = new JPanel(); //Declare the JPanel
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
setContentPane(contentPane); //Add the JPanel
contentPane.setLayout(null); //Set the layout
maxTxtVCC = new JTextField(); //Declare this text field
maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
maxTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtVCC); //Add to the content pane
maxTxtTemp = new JTextField(); //Declare this text field
maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
maxTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtTemp); //Add to the content pane
maxTxtLight = new JTextField(); //Declare this text field
maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
maxTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(maxTxtLight); //Add to the content pane
JLabel lblLight = new JLabel("Light"); //Declare this label
lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblLight.setBounds(22, 469, 46, 17); //Set size and location
contentPane.add(lblLight); //Add to the content pane
JLabel lblTemp = new JLabel("Temperature"); //Declare this label
lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblTemp.setBounds(10, 503, 109, 17); //Set size and location
contentPane.add(lblTemp);
JLabel lblVCC = new JLabel("VCC"); //Declare this label
lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
lblVCC.setBounds(22, 534, 46, 17); //Set size and location
contentPane.add(lblVCC); //Add to the content pane
minTxtLight = new JTextField(); //Declare this text field
minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
minTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtLight); //Add to the content pane
avTxtLight = new JTextField(); //Declare this text field
avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
avTxtLight.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtLight); //Add to the content pane
minTxtTemp = new JTextField(); //Declare this text field
minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
minTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtTemp); //Add to the content pane
avTxtTemp = new JTextField(); //Declare this text field
avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
avTxtTemp.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtTemp); //Add to the content pane
minTxtVCC = new JTextField(); //Declare this text field
minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
minTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(minTxtVCC); //Add to the content pane
avTxtVCC = new JTextField(); //Declare this text field
avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
avTxtVCC.setEditable(false); //Set it so it cannot be edited
contentPane.add(avTxtVCC); //Add to the content pane
btnMax = new JButton("Maximum"); //Declare this button
btnMax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double tempArray1 [] = new double [totalValues];
double tempArray2 [] = new double [totalValues];
double tempArray3 [] = new double [totalValues];
for (int i = 0; i < totalValues; i++){
tempArray1[i] = values[i][0]; //assign the indexes along side each individual sensor from sensor value
tempArray2[i] = values[i][1];
tempArray3[i] = values[i][2];
}
//execute the method defined in Utils.java to calculate maximum
maxTxtLight.setText(findMax(tempArray1)+"");
maxTxtTemp.setText(findMax(tempArray2)+"");
maxTxtVCC.setText(findMax(tempArray3)+"");
}
});
btnMax.setBounds(110, 438, 89, 23); //Set size and location
contentPane.add(btnMax); //Add to the content pane
btnMin = new JButton("Minimum"); //Declare this button
btnMin.setBounds(221, 438, 89, 23); //Set size and location
contentPane.add(btnMin); //Add to the content pane
btnAv = new JButton("Average"); //Declare this button
btnAv.setBounds(328, 438, 89, 23); //Set size and location
contentPane.add(btnAv); //Add to the content pane
textArea = new TextArea(); //Declare this text area
textArea.setBounds(22, 55, 551, 367); //Set size and location
textArea.setEditable(false); //Set it so it cannot be edited
contentPane.add(textArea); //Add to the content pane
btnOpn = new JButton("Open File"); //Declare this button
btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
public void actionPerformed(ActionEvent arg0) { //Method for action performed
try{
fc = new JFileChooser(); //Declare the file chooser
fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type
int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
File f; //Create a file to hold the data
//If the selected file is approved by the file chooser...
if(returnVal == JFileChooser.APPROVE_OPTION){
f = fc.getSelectedFile(); //Stored selected file into file variable
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
textArea.append("\nLoading file...\n\n"); //Print out loading message and some new lines
in.readLine(); //Skip the first line as it's just headers
int index = 0; //Integer used to label the indexes of the array
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
}
totalValues = index; //Set a value to the total values
textArea.append(builder.toString()); //Using the string builder to compile the text
textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
in.close(); //Close the reader.
values = new Double [index][3];
for(int i = 0; i < totalValues; i++){
String cols[] = contentCSV[i].split(",");
String tempMillis = cols[0]; //Use a string to take the millis stamp out of the array
String tempStamp = cols[1]; //Use a string to take the time stamp out of the array
String tempDateTime = cols[2]; //Use a string to take the date stamp out of the array
for(int columns=3;columns<cols.length;++columns){
//temp sensor value holds the 9 sensors and the index numbers, parsing the data into double
values[i][columns-3] = Double.parseDouble(cols[columns]);
}
}
}
else{
f = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
btnOpn.setBounds(484, 26, 89, 23); //Set size and location
contentPane.add(btnOpn); //Add to the content pane
opnTxt = new JTextField(); //Declare this text field
opnTxt.setBounds(22, 27, 452, 20); //Set size and location
opnTxt.setEditable(false); //Set it so it cannot be edited
contentPane.add(opnTxt); //Add to the content pane
}
//Methods for Calculations
public static double findMax(double[] array){
double max;
max = array[0];
for(int i=1;i<array.length;++i){
if(array[i]>max){
max = array[i];
}
}
return max;
}
}
The problem is here:
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
c4 = Double.parseDouble(temp[3]);
c5 = Double.parseDouble(temp[4]);
c6 = Double.parseDouble(temp[5]);
}
Your storing your values into temporary local (local to the while loop) variables.
These variables are re-assigned every loop so you lose the information.
You can do one of two things:
Calculate the running SUM, and number of rows in order to calculate the average at the end. Average = SUM / COUNT
Store all values in arraylists, and calculate average at the end.
Example:
double c4avg=0, c5avg=0, c6avg=0;
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
index++; //increment the index to move the next one up for the next line
String temp[] = line.split(",");
//Calculate Running Sum stored in AVG variable
c4avg += Double.parseDouble(temp[3]);
c5avg += Double.parseDouble(temp[4]);
c6avg += Double.parseDouble(temp[5]);
}
//Divide by total rows to get average
c4avg/=index;
c5avg/=index;
c6avg/=index;
Related
Text area exceeds the window area
I have wrote program in java the program is to convert from KM to miles and miles to KM the program works fine but the problem is in the result in text area exceeded the area so does not appear the full text below the code attached. so i want if it is reached at the end of line it goes to new line import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Converter extends JFrame implements ActionListener { JLabel label = new JLabel("Distance : "); JTextField input = new JTextField(10); JButton button = new JButton("Convert"); JTextArea output = new JTextArea(10,15); CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("Convert MILES to KM", cbg, true); Checkbox cb2 = new Checkbox("Convert KM to MILES", cbg, false); public static void main(String args[]) { Converter s = new Converter(); s.setVisible(true); } public Converter() { setLayout(null); setSize(300,400); //left-down-width-hegiht cb1.setBounds(60,30,150,30); cb2.setBounds(60,60,150,30); label.setBounds(30,90,120,30); input.setBounds(90,95,170,20); button.setBounds(100,130,90,30); output.setBounds(45,168,200,165); add(cb1); add(cb2); add(label); add(input); add(button); add(output); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (cb1.getState() ) { if (e.getSource() == button) { double d = Double.parseDouble(input.getText()); double d2 = d / 0.62; String str2 = String.valueOf(d2); output.setText(d + "miles equals to " + str2 + " kilometers"); } } if (cb2.getState()) { if (e.getSource() == button){ double d = Double.parseDouble(input.getText()); double d2 = d * 0.62; String str2 = String.valueOf(d2); output.setText(d + " kilometers equals to " + str2 + " miles "); } } } }
If your goal is purely to have line wrapping on in the text area then you can make use of JTextArea's built-in function named setLineWrap. Passing a true boolean value as a parameter to setLineWrap such as setLineWrap(true) will turn on line wrapping for the JTextArea component. Passing a false boolean value as a parameter will turn off line wrapping In your code, it would be used as follows. output.setLineWrap(true); The Converter constructor will then look as follows. public Converter() { // Turn on line wrapping. output.setLineWrap(true); setLayout(null); setSize(300, 400); // left-down-width-hegiht cb1.setBounds(60, 30, 150, 30); cb2.setBounds(60, 60, 150, 30); label.setBounds(30, 90, 120, 30); input.setBounds(90, 95, 170, 20); button.setBounds(100, 130, 90, 30); output.setBounds(45, 168, 200, 165); add(cb1); add(cb2); add(label); add(input); add(button); add(output); button.addActionListener(this); }
How can I access variables outside of loop in Java?
So I have my if statements to search a .txt file for the currency codes that correspond to the country the user types in. I store those country codes in Strings called 'from' and 'to'. I need to access the results of the if statements which are stored in the 'from' and 'to' variables to plug into something later. When I try to use these in the line way down at the end it says Cannot find symbol 'from' and Cannot find symbol 'to'. How can I fix this? //all my imports here public class ExchangeApp { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300,400); frame.setTitle("Exchange App"); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(8, 2, 5, 3)); //GUI Elements JLabel toLabel = new JLabel("To"); JTextField CurrencyTo = new JTextField(20); JLabel fromLabel = new JLabel("From"); JTextField CurrencyFrom = new JTextField(20); JLabel amountLabel = new JLabel("Amount"); JTextField AmountText = new JTextField(20); JLabel displayLabel = new JLabel(); JLabel updateLabel = new JLabel(); JButton Calculate = new JButton("Calculate"); JButton Clear = new JButton("Clear"); //Add elements to panel panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); panel.add(fromLabel); panel.add(CurrencyFrom); panel.add(toLabel); panel.add(CurrencyTo); panel.add(amountLabel); panel.add(AmountText); panel.add(Calculate); panel.add(Clear); panel.add(displayLabel); panel.add(updateLabel); //make visible frame.add(panel); frame.setVisible(true); class calculateListener implements ActionListener{ #Override public void actionPerformed(ActionEvent event){ if(event.getSource()==Calculate){ String line, from, to; String fromString = CurrencyFrom.getText(); String toString = CurrencyTo.getText(); double amount = Double.parseDouble(AmountText.getText()); try{ //import text file File inputFile = new File("currency.txt"); //create file scanner Scanner input = new Scanner(inputFile); try{ //skip first line input.nextLine(); //while has next line while(input.hasNextLine()){ //set line equal to entire line line = input.nextLine(); String[] countryArray = line.split("\t"); //search for from if(fromString.equals(countryArray[0])){ //set 'from' equal to that country code from = countryArray[2]; //testing System.out.println(from); } //search for to if(toString.equals(countryArray[0])){ //set 'to' equal to that country code to = countryArray[2]; System.out.println(to); } else{ displayLabel.setText("To country not found"); } }//while loop }//2nd try finally{input.close();} }//1st try catch(IOException exception){ System.out.println(exception); }//catch bracket }//if bracket ****these 2 variables**** String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to; }//action bracket }//class implements action listener bracket ActionListener listener = new calculateListener(); Calculate.addActionListener(listener); }//main bracket }//class bracket
How can I output a user's information entered through a Java Swing GUI onto an excel sheet?
I am writing a program to help keep track of employee seating, however, I am having a difficult time getting the user's information that was captured by a Java Swing GUI to be printed onto an excel sheet. I am using apache POI in order to write to excel as well. The program iterates through the rows on the excel sheet correctly, but it seems to delete the data that is supposed to be on the first row once the user wants to continue to enter more information. If the user enters information just ONCE (Desk number, employee name, the amount of employees at that desk), presses the JButton "Add To List", it prints the information on the first row like it is supposed to. If the user enters information more than once, it increments the amount of times the "Add To List" button is pressed, but only prints out the last input entered by the user leaving other previous instances of information being written onto the excel rows blank. Is it a problem with the way the counter is being incremented? Or is it the textfields that need to be adjusted? I apologize for such a long post, but I am teaching myself how to program in java and this problem has been haunting me for a while. This is my code so far: import java.awt.EventQueue; import java.awt.Window; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.*; import java.io.*; import javax.swing.DropMode; public class userMenu { private JFrame frmUtilizationSeatingReport; //JFrame being used private JTextField txtDeskNum; //Text box that will hold the desk number private JTextField txtEmployeeName; //Text box for employee name private JTextField txtNumAtDesk; //Text box for the number of employees at that desk public int rownum = 1; //My counter being used to increment the row in which input is being stored in public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { userMenu window = new userMenu(); window.frmUtilizationSeatingReport.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public userMenu() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmUtilizationSeatingReport = new JFrame(); frmUtilizationSeatingReport.setTitle("Utilization Seating Report Program"); frmUtilizationSeatingReport.setBounds(100, 100, 436, 210); frmUtilizationSeatingReport.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmUtilizationSeatingReport.getContentPane().setLayout(null); JLabel lblDeskNumber = new JLabel("Desk Number:"); lblDeskNumber.setBounds(20, 11, 163, 21); frmUtilizationSeatingReport.getContentPane().add(lblDeskNumber); txtDeskNum = new JTextField(); txtDeskNum.setBounds(42, 30, 121, 20); frmUtilizationSeatingReport.getContentPane().add(txtDeskNum); txtDeskNum.setColumns(10); JLabel lblEmployeeName = new JLabel("Employee Name:"); lblEmployeeName.setBounds(20, 55, 163, 21); frmUtilizationSeatingReport.getContentPane().add(lblEmployeeName); txtEmployeeName = new JTextField(); txtEmployeeName.setBounds(42, 73, 121, 20); frmUtilizationSeatingReport.getContentPane().add(txtEmployeeName); txtEmployeeName.setColumns(10); JLabel lblNumberOfEmployees = new JLabel("Number of Employees at Desk:"); lblNumberOfEmployees.setBounds(20, 96, 281, 21); frmUtilizationSeatingReport.getContentPane().add(lblNumberOfEmployees); txtNumAtDesk = new JTextField(); txtNumAtDesk.setBounds(42, 115, 121, 20); frmUtilizationSeatingReport.getContentPane().add(txtNumAtDesk); txtNumAtDesk.setColumns(10); JButton btnAdd = new JButton("Add To List"); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent b) { String deskNumber = ""; //Will take the desk number in as a string int empsAtDesk = 0; //The number of employees at the desk as an int String employeeName = ""; //Employee Name boolean keepRunning = true; deskNumber = txtDeskNum.getText(); empsAtDesk = Integer.parseInt(txtNumAtDesk.getText()); employeeName = txtEmployeeName.getText(); //Blank workbook HSSFWorkbook workbook = new HSSFWorkbook(); //Blank sheet HSSFSheet sheet = workbook.createSheet("Seating Details"); //create heading Row rowHeading = sheet.createRow(0); rowHeading.createCell(0).setCellValue("Desk:"); rowHeading.createCell(1).setCellValue("Employee(s)Name:"); rowHeading.createCell(2).setCellValue("Number At Desk:"); //Create 'total' headings Row rowtotal = sheet.createRow(71); rowtotal.createCell(0).setCellValue("Total:"); CellStyle stylerowtotal = workbook.createCellStyle(); Font totalfonts = workbook.createFont(); totalfonts.setBold(true); totalfonts.setFontName(HSSFFont.FONT_ARIAL); totalfonts.setFontHeightInPoints((short) 11); stylerowtotal.setFont(totalfonts); stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER); rowtotal.getCell(0).setCellStyle(stylerowtotal); Row rowpercent = sheet.createRow(72); rowpercent.createCell(0).setCellValue("Total %/Day:"); stylerowtotal = workbook.createCellStyle(); totalfonts = workbook.createFont(); totalfonts.setBold(true); totalfonts.setFontName(HSSFFont.FONT_ARIAL); totalfonts.setFontHeightInPoints((short) 11); stylerowtotal.setFont(totalfonts); stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER); rowpercent.getCell(0).setCellStyle(stylerowtotal); Row percentMTh = sheet.createRow(73); percentMTh.createCell(0).setCellValue("Total %/Week M-Th:"); stylerowtotal = workbook.createCellStyle(); totalfonts = workbook.createFont(); totalfonts.setBold(true); totalfonts.setFontName(HSSFFont.FONT_ARIAL); totalfonts.setFontHeightInPoints((short) 11); stylerowtotal.setFont(totalfonts); stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER); percentMTh.getCell(0).setCellStyle(stylerowtotal); Row percentMFri = sheet.createRow(74); percentMFri.createCell(0).setCellValue("Total %/Week M-F:"); stylerowtotal = workbook.createCellStyle(); totalfonts = workbook.createFont(); totalfonts.setBold(true); totalfonts.setFontName(HSSFFont.FONT_ARIAL); totalfonts.setFontHeightInPoints((short) 11); stylerowtotal.setFont(totalfonts); stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER); percentMFri.getCell(0).setCellStyle(stylerowtotal); Row seatsAvai = sheet.createRow(75); seatsAvai.createCell(0).setCellValue("Total Seats Available:"); stylerowtotal = workbook.createCellStyle(); totalfonts = workbook.createFont(); totalfonts.setBold(true); totalfonts.setFontName(HSSFFont.FONT_ARIAL); totalfonts.setFontHeightInPoints((short) 11); stylerowtotal.setFont(totalfonts); stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER); seatsAvai.getCell(0).setCellStyle(stylerowtotal); //Create Cell Formulas //Total number of employees at a desk cell formula rowtotal.createCell(2).setCellFormula("SUM(C2:C71)"); //Total percentage for the day rowpercent.createCell(2).setCellFormula("(SUM(C2:C71) / 78) * 100"); //Font size and style loop for my headers for(int i = 0; i < 3; i++) { CellStyle stylerowHeading = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); font.setFontName(HSSFFont.FONT_ARIAL); font.setFontHeightInPoints((short) 11); stylerowHeading.setFont(font); stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER); rowHeading.getCell(i).setCellStyle(stylerowHeading); } //This data needs to be written (Object[]) Map <String, Object[]> data = new TreeMap<String, Object[]>(); data.put("5", new Object[] {deskNumber, employeeName, empsAtDesk}); if(keepRunning){ //Iterate over data and write to sheet Set<String> keyset = data.keySet(); for(String Key : keyset) { Row row = sheet.createRow(rownum++); Object [] objArr = data.get(Key); int cellnum = 0; for(Object obj : objArr) { Cell cell = row.createCell(cellnum++); if(obj instanceof String) { cell.setCellValue((String)obj); } else if(obj instanceof Integer) { cell.setCellValue((Integer)obj); } } //Auto size my columns that will be filled out with user input info. for (int i = 0; i < 3; i++) { sheet.autoSizeColumn(i); } } //top for loop brace try{ //save to excel file FileOutputStream out = new FileOutputStream(new File("Employee Seating Report.xls")); workbook.write(out); out.flush(); out.close(); workbook.close(); System.out.println("Excel Written Succesfully..." + '\n'); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1){ e1.printStackTrace(); } catch (Exception e1) { System.out.println(e1.getMessage()); } //Empty text fields once user presses "Add To List" button txtDeskNum.setText(""); txtEmployeeName.setText(""); txtNumAtDesk.setText(""); }//If statement end brace }//Public void end brace }); btnAdd.setBounds(214, 42, 129, 23); frmUtilizationSeatingReport.getContentPane().add(btnAdd); JButton btnExit = new JButton("End Program"); btnExit.addActionListener(new ActionListener() { //If the user presses the"End Program" button, close the program. public void actionPerformed(ActionEvent e) { System.exit(0); } }); btnExit.setBounds(214, 95, 129, 23); frmUtilizationSeatingReport.getContentPane().add(btnExit); } }
You are creating your workbook inside your addActionListener and writing a new Excel file in it, so it will always overwrite the previous written data. Try collecting all the data to a List of objects EmployeeDesk on click of your button btnAdd and create a new button that creates the workbook and writes the data from your list to your Excel, so you'll have a new button btnSave that creates the Excel file and writes everthing.
I'm not an expert of the .xls format and haven't used it but i've written to csv files and you can use the java standard library to do so fairly simply. Maybe a jtable would remove some of the ambiguity you have with creating rows columns and headers. It would certainly be less verbose.
delete previous content from JTable every time button event happens
I'm having a hard time removing data from my JTable. I've tried JTable .repaint(), setRowCount(0) , also model.removeRow(). I created print statements to see the row count when using setRowCount and the rows do become 0 however my table does not update. This is the last part of this project I need to implement. I'm not sure why my table isn't updating because I am altering the model with removeRow as well as setRowCount. If you guys could guide me in the right direction I would appreciate it. public class TemplateGui extends JFrame { private final ButtonGroup buttonGroup = new ButtonGroup(); private JTextField textField; private static String [] sortedRoles_Flags,finalFlagsArr,finalHSArr; private static String finalFlags="",finalHS="",columnToConvert="Result"; private Vector<String> SF,HS,column; private JTable hotelSecurityTable,securityFlagsTable; private DefaultTableModel hsTableModel,sfTableModel; public TemplateGui(){ super("Galaxy Template Generator V1.0"); //column name column = new Vector(Arrays.asList(columnToConvert)); getContentPane().setForeground(new Color(0, 0, 0)); getContentPane().setLayout(null); getContentPane().setBackground(new Color(51, 51, 51)); //radio buttons JRadioButton rdbtnNewRadioButton = new JRadioButton("Central User "); rdbtnNewRadioButton.setFont(new Font("Tahoma", Font.BOLD, 11)); rdbtnNewRadioButton.setBackground(Color.WHITE); buttonGroup.add(rdbtnNewRadioButton); rdbtnNewRadioButton.setBounds(222, 75, 127, 36); getContentPane().add(rdbtnNewRadioButton); final JRadioButton rdbtnPropertyUser = new JRadioButton("Property User"); rdbtnPropertyUser.setFont(new Font("Tahoma", Font.BOLD, 11)); rdbtnPropertyUser.setBackground(Color.WHITE); buttonGroup.add(rdbtnPropertyUser); rdbtnPropertyUser.setBounds(222, 38, 127, 34); getContentPane().add(rdbtnPropertyUser); textField = new JTextField(); textField.setFont(new Font("Tahoma", Font.BOLD, 18)); textField.setBounds(10, 35, 53, 34); getContentPane().add(textField); textField.setColumns(10); JLabel lblHotelSecurity = new JLabel("Hotel Security (H S)"); lblHotelSecurity.setHorizontalAlignment(SwingConstants.CENTER); lblHotelSecurity.setFont(new Font("Tahoma", Font.BOLD, 13)); lblHotelSecurity.setBounds(10, 144, 189, 23); lblHotelSecurity.setBackground(new Color(204, 204, 204)); lblHotelSecurity.setOpaque(true); getContentPane().add(lblHotelSecurity); JLabel label = new JLabel("Security Flags (S F)"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setFont(new Font("Tahoma", Font.BOLD, 13)); label.setBounds(222, 144, 372, 23); label.setBackground(new Color(204, 204, 204)); label.setOpaque(true); getContentPane().add(label); JLabel lblEnterTemplateCode = new JLabel("ENTER TEMPLATE CODE"); lblEnterTemplateCode.setForeground(new Color(255, 255, 255)); lblEnterTemplateCode.setFont(new Font("Tahoma", Font.BOLD, 14)); lblEnterTemplateCode.setBounds(10, 9, 175, 23); getContentPane().add(lblEnterTemplateCode); JLabel lblSelectUserRole = new JLabel("SELECT USER ROLE LEVEL"); lblSelectUserRole.setForeground(new Color(255, 255, 255)); lblSelectUserRole.setFont(new Font("Tahoma", Font.BOLD, 14)); lblSelectUserRole.setBounds(222, 13, 195, 14); getContentPane().add(lblSelectUserRole); //Submit button action Button button = new Button("Generate Template"); button.setFont(new Font("Dialog", Font.BOLD, 12)); button.setBackground(new Color(102, 255, 102)); button.setForeground(Color.BLACK); button.setBounds(467, 83, 127, 41); getContentPane().add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Query excell = new Query(); //get template text String template = textField.getText().toUpperCase(); System.out.println(template); if(rdbtnPropertyUser.isSelected()){ try { //property user was selected excell.runProcess(1); System.out.println("you selected Property user"); } catch (IOException e) { e.printStackTrace(); } } else{ try { //Central User was selected excell.runProcess(2); System.out.println("you selected central user"); } catch (IOException e) { e.printStackTrace(); } } System.out.println("NOW WERE HERE"); //get static variables from Excel Query for(int i = 0; i< Query.sortedGF.length; i++) { if(Query.sortedGF[i].contains(template)){ sortedRoles_Flags =Query.sortedGF[i].split(" "); System.out.println("THIS RAN"+" :"+i); break; } } //add data to table int j=1; int sizeOfFlags = Query.securityFlags.length; //Add HS to FinalHS Variable only if Yes for(int i=0;i< sortedRoles_Flags.length+1-sizeOfFlags;i++) { if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y")) { System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]); finalHS += Query.hotelSecurity[i]+"+"; System.out.println("Hotel security:"+" "+finalHS); } } //add Security Flags to Final Flags for(int i=(sortedRoles_Flags.length-sizeOfFlags+1);i< sortedRoles_Flags.length;i++) { finalFlags += Query.securityFlags[j]+"\t\t: "+ sortedRoles_Flags[i]+" + "; j++; } //Leave open just incase they would prefer a text file for template in which case we just write it System.out.println(finalFlags); System.out.println(finalHS); //Convert to String Arrays in order to add to our JTable finalFlagsArr= finalFlags.split("\\+"); finalHSArr = finalHS.split("\\+"); for(int i=0; i <finalHSArr.length;i++) finalHSArr[i].replaceAll(" ",""); hsTableModel.setRowCount(0); for (String row : finalHSArr) { hsTableModel.addRow(new Object[]{row}); } sfTableModel.setRowCount(0); for (String row : finalFlagsArr) { sfTableModel.addRow(new Object[]{row}); } } }); //scroll panes for flags JScrollPane scrollPaneHS = new JScrollPane(); scrollPaneHS.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPaneHS.setBounds(10, 170, 189, 185); getContentPane().add(scrollPaneHS); JScrollPane scrollPaneSF = new JScrollPane(); scrollPaneSF.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPaneSF.setBounds(222, 170, 372, 187); getContentPane().add(scrollPaneSF); //tables for updates hsTableModel = new DefaultTableModel(HS,column); hotelSecurityTable = new JTable(hsTableModel); hotelSecurityTable.setBackground(new Color(255, 255, 255)); scrollPaneHS.setViewportView(hotelSecurityTable); sfTableModel = new DefaultTableModel(SF,column); securityFlagsTable = new JTable(sfTableModel); scrollPaneSF.setViewportView(securityFlagsTable); } } Update my latest attempt. It seemed to work but not the second time around. if(hsTableModel.getRowCount() !=0 && sfTableModel.getRowCount() !=0){ for(int i=0; i<hsTableModel.getRowCount();i++) hsTableModel.removeRow(i); for(int i=0; i<sfTableModel.getRowCount();i++) sfTableModel.removeRow(i); sfTableModel.fireTableRowsDeleted(0, sfTableModel.getRowCount()-1); hsTableModel.fireTableRowsDeleted(0, hsTableModel.getRowCount()-1); }
when using setRowCount and the rows do become 0 however my table does not update. Since you are using a DefaultTableModel, the setRowCount(0) is the proper method to use to clear the model of all the entries. The should automatically repaint itself. Create a simple SSCCE that demonstrates your problem. The SSCCE should consist of a JTable with data, and then a JButton to invoke the setRowCount() method. Prove to yourself that the basic concept works and then determine why you real code doesn't. If the table does not repaint then it usually means you are invoking the setRowCount() method on a TableModel that has NOT be added to the JTable that is visible on the GUI. Also, don't: use Button. You should be using a JButton use a null layout. Swing was designed to be used with Layout Managers.
setRowCount(0) works. I was forgetting to reset the string Values of finalHS =""; finalFlags=""; Therefore the table was printing out the values stored in the variable. I had the variables obtain their data through += Method as seen below. Next time I will SSCCE before posting. for(int i=0;i< sortedRoles_Flags.length+1-sizeOfFlags;i++) { if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y")) { System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]); finalHS += Query.hotelSecurity[i]+"+"; System.out.println("Hotel security:"+" "+finalHS); } } //add Security Flags to Final Flags for(int i=(sortedRoles_Flags.length-sizeOfFlags+1);i< sortedRoles_Flags.length;i++) { finalFlags += Query.securityFlags[j]+"\t\t: "+ sortedRoles_Flags[i]+" + "; j++; }
How To Keep Size Of JTextArea constant?
I'm using an object of JTextArea in my application which deals with sending sms. I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only Enter key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this. Below is my code. Please check it. class Send_sms extends JPanel implements ActionListener,DocumentListener { JButton send; JTextArea smst; JLabel title,limit; JPanel mainp,titlep,sendp,wrap,titlewrap,blankp1,blankp2,sendwrap; JScrollPane scroll; Border br,blackbr; Boolean flag = false; PlainDocument plane; public static final int LINES = 4; public static final int CHAR_PER_LINE = 40; //character limit 160 for a sms public Send_sms() { br = BorderFactory.createLineBorder(Color.RED); blackbr = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.DARK_GRAY,Color.GRAY); setBorder(blackbr); title = new JLabel("Enter the text you want to send!"); title.setFont(new Font("",Font.BOLD,17)); limit = new JLabel(""+charCount+" Characters"); smst = new JTextArea(LINES,CHAR_PER_LINE); smst.setSize(100,100); plane = (PlainDocument)smst.getDocument(); //adding DocumentSizeFilter 2 keep track of characters entered plane.setDocumentFilter(new DocumentSizeFilter(charCount)); plane.addDocumentListener(this); send = new JButton("Send"); send.setToolTipText("Click Here To Send SMS"); send.addActionListener(this); //scroll = new JScrollPane(smst); //scroll.setPreferredSize(new Dimension(200,200)); //scroll.setVerticalScrollBarPolicy(null); //scroll.setHorizontalScrollBarPolicy(null); smst.setBorder(br); blankp1 = new JPanel(); blankp2 = new JPanel(); titlep = new JPanel(new FlowLayout(FlowLayout.CENTER)); titlewrap = new JPanel(new GridLayout(2,1)); mainp = new JPanel(new BorderLayout()); sendwrap = new JPanel(new GridLayout(3,1)); sendp = new JPanel(new FlowLayout(FlowLayout.CENTER)); wrap = new JPanel(new BorderLayout()); titlep.add(title); titlewrap.add(titlep); titlewrap.add(blankp1); sendp.add(send); sendwrap.add(limit); sendwrap.add(blankp2); sendwrap.add(sendp); wrap.add(smst,BorderLayout.CENTER); mainp.add(titlewrap,BorderLayout.NORTH); mainp.add(wrap,BorderLayout.CENTER); mainp.add(sendwrap,BorderLayout.SOUTH); add(mainp); } public void actionPerformed(ActionEvent e) { Vector<Vector<String>> info = new Vector<Vector<String>> (); Vector<String> numbers = new Vector<String>(); if(e.getSource() == send) { //Call a function to send he message to all the clients using text //charCount = 165; String msg = smst.getText(); if(msg.length() == 0) JOptionPane.showMessageDialog(null,"Please Enter Message","Error",JOptionPane.ERROR_MESSAGE); else { // System.out.println("Message:"+msg); Viewdata frame = new Viewdata(msg); limit.setText(""+charCount+" Characters"); charCount = 160; } } } public void insertUpdate(DocumentEvent e) { System.out.println("The legth:(insert) "+e.getLength()); for(int i = 0;i<e.getLength(); i++) { if(charCount >0) charCount--; else break; } limit.setText(""+charCount+" Characters"); } public void removeUpdate(DocumentEvent e) { //System.out.println("The legth(remove): "+e.getLength()); for(int i = 0;i<e.getLength(); i++) { charCount++; } limit.setText(""+charCount+" Characters"); } public void changedUpdate(DocumentEvent e) { //System.out.println("The legth(change): "+e.getLength()); } }//end Send_sms
Sound like you are creating the text area using JTextArea textArea = new JTextArea(); When using this format the text area doesn't have a preferred size so it keeps on growing. If you use: JTextArea textArea = new JTextArea(2, 30); JScrollPane scrollPane = new JScrollPane( textArea ); Then the text area will have a preferred size of 2 rows and (roughly) 30 columns. As you type when you exceed the preferred width the horizontal scrollbar will appear. Or if you turn on wrapping, then the text will wrap and a vertical scrollbar will appear.
you need to specify: textArea.setColumns (160); textArea.setLineWrap (true); textArea.setWrapStyleWord (false); //default But the real problem is that you allow to input more than 160 characters. You need to create some kind of validator which will skip all inputed characters when there are already 160 characters written.
Initialise the textArea with a document that extends PlainDocument and in the insertString method limit the characters to 160