How to take the values of the dynamic textfield?
I suppose to set number of textfields I want at beginning of my program and set the values in this fields and write it into txt file
// this is the foreach loop suppose to take the values and send them to addburst function
for( JTextField f : bt )
{
Burst b = new Burst();
b.addBurst(Integer.parseInt(f.getText()));
}
*addburst function
public boolean addBurst(int x) {
if (FManger.write(x, BurstFileName, true)) {
return true;
} else {
return false;
}
}
*Write Function
public boolean write(int Query, String FilePath, boolean appendType) {
PrintWriter writter = null;
try {
System.out.print("\nwritting in ! " + FilePath);
writter = new PrintWriter(new FileWriter(new File(FilePath),
appendType));
writter.println(Query);
System.out.println(" ... Done ! ");
return true;
} catch (IOException e) {
System.out.println(e);
} finally {
writter.close();
}
return false;
}
I added the dynamic textfields by the constructor
public FillData(int x) {
initComponents();
getContentPane().setBackground(Color.ORANGE);
PnoPanel.setLayout(new GridLayout(x,2));
BuPanel.setLayout(new GridLayout(x,2));
ArrPanel.setLayout(new GridLayout(x,2));
JLabel ProcessNumber[] = new JLabel[x];
JTextField BurstTime[] = new JTextField[x];
JTextField ArrivalTime[] = new JTextField[x];
for (int i = 0; i < x; i++)
{
ProcessNumber[i] = new JLabel(" Process "+(i+1));
BurstTime[i] = new JTextField();
ArrivalTime[i] = new JTextField();
PnoPanel.add(ProcessNumber[i]);
BuPanel.add(BurstTime[i]);
ArrPanel.add(ArrivalTime[i]);
}
}
x is the number of textfields
Related
I have to figure out a way to re-open a file that was initially an output file in order to make my program work.
My program needs to read from the input file first and then write to an output file.
Then I will prompt the user to enter code here`e option to input more or search any data from the output file.
My program starts with the option to 1-Insert more data, 2-Search Data, 3-Quit program.
I could close the I/O files after the user has input more data, but what if the user wants to search data first?
if(readFile==0)
{
FileReader inFile = new FileReader("DATA4STUDENTS.txt");
BufferedReader br = new BufferedReader(inFile);
FileWriter fw1 = new FileWriter("PASSED_STUDENTS.txt");
BufferedWriter bw1= new BufferedWriter(fw1);//Files i want to write and read again later on in the same program.
FileWriter fw2 = new FileWriter("FAILED_STUDENTS.txt");
BufferedWriter bw2 = new BufferedWriter(fw2);
PrintWriter pw1 = new PrintWriter(bw1);
PrintWriter pw2 = new PrintWriter(bw2);
pw1.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw1.println();
pw2.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw2.println();
int index=0;
Assessment [] a = new Assessment[100];
Assessment [] b = new Assessment[100];
double[] CM=new double[100]; //array for CarryMark
double[] FM= new double[100]; //array for FullMark
boolean[] PG=new boolean[100]; //array for Passing-Grade
while(((inData=br.readLine()) !=null))
{
StringTokenizer st = new StringTokenizer(inData,"#");
StudName=st.nextToken();
StudID=st.nextToken();
SubName=st.nextToken();
FullOn=Integer.parseInt(st.nextToken());
FullEX=Integer.parseInt(st.nextToken());
mark=Double.parseDouble(st.nextToken());
fullM=Integer.parseInt(st.nextToken());
EMark=Double.parseDouble(st.nextToken());
fullEM=Integer.parseInt(st.nextToken());
a[index]=new Ongoing_Assessment(StudName, StudID, SubName,FullOn, FullEX, mark, fullM);
b[index]=new Final_Exam_Assessment(StudName, StudID, SubName,FullOn,FullEX,EMark, fullEM);
if(a[index] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[index];
CM[index]=OA.getFinalMark();
}
if(b[index] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[index];
FM[index]=FEA.getFinalMark();
}
if((CM[index]+FM[index])>=a[index].PassingGrade())
{
PG[index]=true;
}
else
{
PG[index]=false;
}
index++;
}
for(int i=0;i<index;i++)
{
String mss=" ";
String mss1=" ";
String mss2=" ";
String grade=" ";
double grade2=0.00;
if(PG[i])
{
mss="PASS";
}
else
{
mss="FAIL";
}
if(a[i] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[i];
mss1=OA.toString();
}
if(b[i] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[i];
mss2=FEA.toString();
}
if(mss.equals("PASS"))
{
if((CM[i]+FM[i])>=91 &&(CM[i]+FM[i])<=100)
{
grade="A+";
grade2=4.00;
}
else if((CM[i]+FM[i])>=80 &&(CM[i]+FM[i])<=90)
{
grade="A";
grade2=4.00;
}
else if((CM[i]+FM[i])>=75 &&(CM[i]+FM[i])<=79)
{
grade="A-";
grade2=3.67;
}
else if((CM[i]+FM[i])>=70 &&(CM[i]+FM[i])<=74)
{
grade="B+";
grade2=3.33;
}
else if((CM[i]+FM[i])>=65 &&(CM[i]+FM[i])<=69)
{
grade="B";
grade2=3.00;
}
else if((CM[i]+FM[i])>=60 &&(CM[i]+FM[i])<=64)
{
grade="B-";
grade2=2.67;
}
else if((CM[i]+FM[i])>=55 &&(CM[i]+FM[i])<=59)
{
grade="C+";
grade2=2.33;
}
else if((CM[i]+FM[i])>=50 &&(CM[i]+FM[i])<=54)
{
grade="C";
grade2=2.00;
}
}
else if(mss.equals("FAIL"))
{
if((CM[i]+FM[i])>=47 &&(CM[i]+FM[i])<=49)
{
grade="C-";
grade2=1.67;
}
else if((CM[i]+FM[i])>=44 &&(CM[i]+FM[i])<=46)
{
grade="D+";
grade2=1.33;
}
else if((CM[i]+FM[i])>=40 &&(CM[i]+FM[i])<=43)
{
grade="D";
grade2=1.00;
}
else if((CM[i]+FM[i])>=30 &&(CM[i]+FM[i])<=39)
{
grade="E";
grade2=0.67;
}
else if((CM[i]+FM[i])>=0 &&(CM[i]+FM[i])<=29)
{
grade="F";
grade2=0.00;
}
}
if(mss.equals("PASS"))
{
**strong text**pw1.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%\t\t"+mss+"\t"+grade+"\t"+df.format(grade2));
pw1.println();
}
else
{
pw2.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%"+mss+"\t"+grade+"\t"+df.format(grade2));
pw2.println();
}
}
br.close();
pw1.close();
pw2.close();
}
Files cannot be reopened after they are closed. There is no way do that without recreating a object.
See https://stackoverflow.com/a/12347891/10818862 for more information.
This is a simple vending machine.
As shown below, I am trying to handle the event of a button click from a frame in the actionPerformed() method.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == drink) {
int i = 0;
try {
File fl = new File("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
product[i] = new Products(productName, productPrice, productAmount);
i = i + 1;
}
object.checkoutDrinks(product);
} catch (IOException exc) {
File fl = new File("Product List.txt");
}
}
if (e.getSource() == snack) {
int i = 0;
try {
File fl = new File("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
product[i] = new Products(productName, productPrice, productAmount);
i = i + 1;
}
object.checkoutSnacks(product);
} catch (IOException exc) {
File fl = new File("Product List.txt");
}
}
I am trying to read from an existing file and instantiate another class with those values.
The problem is when the click event is sent and passed to the method above, the next frame will not show. I thought that it could not be registering the event but it actually was.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
my progress bar is update only to 100%. i check with printing and it's seems everything run as it should be but the UI does not update according to the parameters in the printing check!
here is my Panel class. the main class create frame the adding the MyPanel i create:
public class MyPanel extends JPanel {
File[] DFLIST;
File DF[];
File INP;
File LOG;
JButton chooseDF = new JButton("Choose defect file");
JButton chooseLog = new JButton("Choose log file");
JButton chooseInp = new JButton("Choose inp file");
JButton analayze = new JButton("Analayze");
DefectFileReader[] dfReader;
Document[] docArray;
boolean DFloaded = false;
boolean LOGloaded = false;
boolean INPloaded = false;
Checkbox recipeName;
Checkbox inspectionDuration;
Checkbox area;
Checkbox numberOfDefects;
Checkbox numberOfDefectsPerDetector;
Checkbox sensetivityName;
Checkbox SlicesDetected;
private static int rowIndex = 2;
private static int cellIndex = 4;
FileOutputStream fos;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("analyze_result");
Row row = sheet.createRow(rowIndex);
Cell cell = row.createCell(cellIndex);
XSSFCellStyle csForFirstWrite = workbook.createCellStyle();
XSSFCellStyle csForSecondWrite = workbook.createCellStyle();
XSSFFont fontForBold = workbook.createFont();
XSSFFont fontNotForBold = workbook.createFont();
String totalDuration = "00:00:00";
private int currentFolder = 0;
//TwoRoot t;
JProgressBar pBar = new JProgressBar();
Frame frame = new Frame("Progress Bar");
MyprogressBar taskBar;
/* creating the main panel of the frame - divided to 3 parts. in the north pictures , in the west checkbox , in the east the file chooser */
public MyPanel(){
this.setLayout(new BorderLayout());
this.add(pictureInNorth() , BorderLayout.NORTH);
this.add(checkBoxPanel() , BorderLayout.WEST);
this.add(chooseFilesPanel() , BorderLayout.EAST);
//pBar.setForeground(Color.black);
//pBar.setStringPainted(true);
//this.add(pBar , BorderLayout.SOUTH);
}
/* creating the north panel with the picture */
private JPanel pictureInNorth(){
JPanel toReturn = new JPanel();
toReturn.setBackground(Color.black);
JButton analayzerPic = new JButton(new ImageIcon(new ImageIcon("C:/Users/uvalerx073037/workspace/Analayzer_GUI_Ver2/src/Images/vXqyQkOv.jpeg")
.getImage().getScaledInstance(600, 30,
java.awt.Image.SCALE_SMOOTH)));
analayzerPic.setBackground(Color.black);
toReturn.add(analayzerPic);
return toReturn;
}
/* creating the checkBox in the west */
private JPanel checkBoxPanel(){
recipeName = new Checkbox("Recipe Name" , false);
inspectionDuration = new Checkbox("Inspection Duration" , false);
area = new Checkbox("Area" , false);
numberOfDefects = new Checkbox("Number Of Defects" , false);
numberOfDefectsPerDetector = new Checkbox("Number Of Defects Per Detector", false);
sensetivityName = new Checkbox("Sensetivity Name", false);
SlicesDetected = new Checkbox("Slices were detected" , false);
JPanel toReturn = new JPanel();
toReturn.setLayout(new BoxLayout(toReturn, BoxLayout.Y_AXIS));
toReturn.add(recipeName);
toReturn.add(inspectionDuration);
toReturn.add(numberOfDefects);
toReturn.add(numberOfDefectsPerDetector);
toReturn.add(sensetivityName);
toReturn.add(SlicesDetected);
toReturn.add(area);
return toReturn;
}
/*creating the file chooser in the east */
private Box chooseFilesPanel(){
MyActionListener lis = new MyActionListener();
chooseDF.addActionListener(lis);
chooseInp.addActionListener(lis);
chooseLog.addActionListener(lis);
analayze.addActionListener(lis);
analayze.setForeground(Color.BLUE);
Box toReturn = Box.createVerticalBox();
toReturn.add(Box.createGlue());
toReturn.add(chooseDF);
toReturn.add(Box.createGlue());
toReturn.add(chooseLog);
toReturn.add(Box.createGlue());
toReturn.add(chooseInp);
toReturn.add(Box.createGlue());
toReturn.add(analayze).setSize(50,50);
return toReturn;
}
/* function to check after the user clicked on the analyze button if all the conditions are OK */
public Boolean isValidToStart(){
if(DFloaded == false && LOGloaded == false && INPloaded == false){
JOptionPane.showMessageDialog(null, "NO FILE WAS LOADED!!!", "User Error" , JOptionPane.ERROR_MESSAGE);
return false;
}
if(recipeName.getState() == false && inspectionDuration.getState() == false && area.getState() == false &&
numberOfDefects.getState() == false && numberOfDefectsPerDetector.getState() == false && sensetivityName.getState() == false){
JOptionPane.showMessageDialog(null , "NO CHECK BOX WAS MARKED!!!" + "\n" + "WHAT DATA WOULD YOU LIKE TO COLLECT?" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(area.getState() == true && (LOGloaded == false || DFloaded == false || INPloaded == false)){
JOptionPane.showMessageDialog(null , "IF YOU WANT TO COLLECT AERA YOU NEED TO CHOOSE INP + LOG + DEF" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
if(SlicesDetected.getState() == true && LOGloaded == false){
JOptionPane.showMessageDialog(null , "You need to load the LOG in order to get the amount of slices were detected!" , "User Error" , JOptionPane.ERROR_MESSAGE );
return false;
}
else
return true;
}
/* build the row of the titles , only what the user marked in the check box */
private void firstWriteToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontForBold.setBold(true);
csForFirstWrite.setFont(fontForBold);
csForFirstWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.lightGray));
csForFirstWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForFirstWrite.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
csForFirstWrite.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
if(recipeName.getState() == true){
row = sheet.createRow(rowIndex - 1);
row.createCell(cellIndex).setCellValue("Recipe Name: " + curDF.getRecipeName());
sheet.autoSizeColumn(cellIndex);
}
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex).setCellValue("inspection index");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
if(numberOfDefects.getState() == true){
row.createCell(cellIndex).setCellValue("Total Defects");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
toOtherFunc = curDF.getDetectorNames();
for(int i=0; i < toOtherFunc.size() ; i++){
row.createCell(cellIndex).setCellValue(toOtherFunc.get(i));
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
}
if(sensetivityName.getState() == true){
row.createCell(cellIndex).setCellValue("sensetivity Name");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(LOGloaded == true){
row.createCell(cellIndex).setCellValue("Slices were detected");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true){
row.createCell(cellIndex).setCellValue("Inspection Duration");
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
for (Row row : sheet){
for (Cell cell_local : row){
cell_local.setCellStyle(csForFirstWrite);
}
}
System.out.println("row index is: " + rowIndex + "cell index is: " + cellIndex);
}
/* fill the excel in the data were collected */
private void writeToExcel(DefectFileReader curDF , XSSFSheet sheet , XSSFWorkbook workbook , FileOutputStream fos) throws Exception{
fontNotForBold.setBold(false);
csForSecondWrite.setFont(fontNotForBold);
csForSecondWrite.setFillForegroundColor(new XSSFColor(java.awt.Color.white));
csForSecondWrite.setFillPattern(CellStyle.SOLID_FOREGROUND);
csForSecondWrite.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderTop(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderRight(XSSFCellStyle.BORDER_THIN);
csForSecondWrite.setBorderLeft(XSSFCellStyle.BORDER_THIN);
cellIndex = 4;
row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++).setCellValue("inspection_" + (rowIndex - 3));
if(numberOfDefects.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getTotalDefects());
if(numberOfDefectsPerDetector.getState() == true){
ArrayList<String> toOtherFunc = new ArrayList<String>();
int[] toPrintNumber = new int[toOtherFunc.size()];
toOtherFunc = curDF.getDetectorNames();
System.out.println(toOtherFunc);
toPrintNumber = curDF.getDefectPerDetector(toOtherFunc);
for(int i=0; i < toOtherFunc.size() ; i++)
row.createCell(cellIndex++).setCellValue(toPrintNumber[i]);
}
if(sensetivityName.getState() == true)
row.createCell(cellIndex++).setCellValue(curDF.getSensetivityName());
if(LOGloaded == true){
LogFileReader logReader = new LogFileReader(LOG , curDF.getInspectionEndTime());
ArrayList<String> toLog = curDF.getRunsIndex();
String toPrint = "";
for(int i=0 ; i < toLog.size() ; i = i+2)
toPrint += toLog.get(i) + ": " + logReader.diagnozeLog(toLog.get(i+1)) + " ";
if(toPrint.equals(""))
row.createCell(cellIndex).setCellValue("The data of this run is not in this log!");
else
row.createCell(cellIndex).setCellValue(toPrint);
sheet.autoSizeColumn(cellIndex);
cellIndex++;
}
if(inspectionDuration.getState()==true)
row.createCell(cellIndex++).setCellValue(curDF.inspectionDuration());
for (Row row : sheet){
if( row.getRowNum() > 2){
for (Cell cell_local : row){
cell_local.setCellStyle(csForSecondWrite);
}
}
}
System.out.println("row index is: " + rowIndex + " cell index is: " + cellIndex);
}
/* adding the inspection time of the current run to the total time */
public String sumTimes(String time1) {
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.printZeroAlways()
.appendHours()
.appendLiteral(":")
.appendMinutes()
.appendLiteral(":")
.appendSeconds()
.toFormatter();
org.joda.time.Period period1 = formatter.parsePeriod(time1);
org.joda.time.Period period2 = formatter.parsePeriod(totalDuration);
return formatter.print(period2.plus(period1).normalizedStandard());
}
public void initializeFrame(){
frame.setSize(300, 100);
pBar.setForeground(Color.black);
pBar.setStringPainted(true);
frame.add(pBar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyprogressBar extends SwingWorker<Void, Integer> {
JProgressBar pBar;
int max;
int currentFolder;
public MyprogressBar(JProgressBar curBar , int max , int currentFolder){
this.pBar = curBar;
this.max = max;
this.currentFolder = currentFolder;
}
public void done(){
}
#Override
protected Void doInBackground() throws Exception {
System.out.println("i'm in background");
double i = currentFolder;
double t = DFLIST.length;
double toSetInDouble = (i/t);
int toSet = (int) (toSetInDouble * 100);
pBar.setValue(toSet);
System.out.println(toSet);
repaint();
Thread.sleep(10);
publish(toSet);
return null;
}
}
/* adding listener to all of the buttons and check boxes */
public class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource() == chooseDF){
File directory;
FilenameFilter f = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.length()<=2;
}
};
FilenameFilter def = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".def");
}
};
JFileChooser chooser = new JFileChooser(System.getProperties().getProperty("user.dir"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
DFloaded = true;
directory = chooser.getSelectedFile();
File[] fileList = directory.listFiles(f);
Arrays.sort(fileList , new NaturalOrderComparator());
DFLIST = new File[fileList.length];
for(int i = 0 ; i<fileList.length ; i++){
File[] tmp = fileList[i].listFiles(def);
for(int j=0 ; j<tmp.length ; j++)
DFLIST[i] = tmp[j];
}
}
}
if(click.getSource() == chooseInp){
JFileChooser fc2 = new JFileChooser();
if (fc2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
INPloaded = true;
INP = fc2.getSelectedFile();
}
}
if(click.getSource() == chooseLog){
JFileChooser fc3 = new JFileChooser();
if(fc3.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
LOGloaded = true;
LOG = fc3.getSelectedFile();
}
}
if(click.getSource() == analayze){
Boolean valid = isValidToStart();
if(valid == true){
try{
fos = new FileOutputStream("c:/temp/analayze.xlsx");
if(DFloaded == true){
try {
initializeFrame();
DF = new File[DFLIST.length];
dfReader = new DefectFileReader[DFLIST.length];
docArray = new Document[DFLIST.length];
for( ; currentFolder < DFLIST.length ; currentFolder++){
new MyprogressBar(pBar, 100, currentFolder + 1).execute();
frame.repaint();
System.out.println("i'm sending the file down here to parse from file to document");
System.out.println(DFLIST[currentFolder].getAbsoluteFile());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
docArray[currentFolder] = (Document) db.parse(DFLIST[currentFolder]);
docArray[currentFolder].getDocumentElement().normalize();
dfReader[currentFolder] = new DefectFileReader(DFLIST[currentFolder] , docArray[currentFolder]);
dfReader[currentFolder].getRunsIndex();
totalDuration = sumTimes(dfReader[currentFolder].inspectionDuration());
if(currentFolder==0){
firstWriteToExcel(dfReader[0], sheet, workbook, fos);
writeToExcel(dfReader[0], sheet, workbook, fos);
}
if(currentFolder!=0)
writeToExcel(dfReader[currentFolder] , sheet , workbook , fos );
repaint();
if(INPloaded == true){
}
DFLIST[currentFolder] = null;
dfReader[currentFolder].clearDfReader();
docArray[currentFolder] = null;
System.gc();
}
}
catch(Exception e ) {
System.out.println(e);
System.exit(0);
}
}
row = sheet.createRow(rowIndex);
totalDuration = sumTimes("00:00:00");
if(inspectionDuration.getState() == true){
row.createCell(cellIndex - 1).setCellValue(totalDuration);
row.getCell(cellIndex - 1).setCellStyle(csForFirstWrite);
}
((Workbook) workbook).write(fos);
workbook.close();
JOptionPane.showMessageDialog(null, "Your data has been analyze!\n you can find the result in c:\\temp");
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
#Udi it would have been really great if you could have pasted a structured code. However, with whatever code you pasted, here is an indicative solution using swingworker. You just need to call your whole actionPerformed() code from doInBackground() of swingworker. Hope it helps.
Moreover, I find the java docs of swingworker a very useful to understand how it works. Examples are very simple yet well explained.
https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html
// use this code inside actionPerformed()
new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
// all your code goes here
for( ; currentFolder < DFLIST.length ; currentFolder++){
double f = currentFolder + 1;
double t = DFLIST.length;
double currentPercentInDouble = (f / t);
int currentPercent = (int) (currentPercentInDouble * 100);
// send the current progress to progress bar. This needs to be updated to progress bar in process() method
publish(currentPercent)
}
// rest of the code
}
#Override
protected void process(List<V> chunks) {
// update the progress bar here
}
}.execute();
So Integer N here is controlled by a JComboBox basically a drop down menu 1-4. My problem is that I get a nullpointerexception error when I initially set N from the box..any ideas how to fix this? I tested it by printing out what N was in both actionlistener instances and it's null in the first one and it's correct in the second one.
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab10 extends JPanel
{
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2;
private JButton load, go,go2;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab10()
{
string = new StringBuilder();
string2 = new StringBuilder();
string3 = new StringBuilder();
string4 = new StringBuilder();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
textarea.setText("");
}
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab10());
frame.pack();
frame.setVisible(true);
}
}
Your question doesn't make sense as written:
Integer N = input.getSelectedIndex()+1;
System.out.println(N);
The println cannot possibly tell you that N is null.
If the expression on the RHS of the = executes without an exception, then N is guaranteed to be non-null. The getSelectedIndex() call returns an int, and the result of the addition will be an int. That will then be autoboxed to an Integer, and autoboxing can NEVER give you a null.
If the expression on the RHS of the = throws an exception, then the println statement won't be executed.
In other words, what you are describing is Impossible.
So what I think is actually happening is one of the following:
Your code is throwing a NullPointerException in the first statement because input is null, and you have misdiagnosed that as meaning that N is null.
This code is sufficiently different from your actual code that it is not possible to understand what is really going on.
You have made a mistake in the compiling / running / deploying of your code, such that you are running a stale binary.
Your code isn't compilable the way it is now. You can't have multiple public classes in the same file. Also, to access the selected index from a JComboBox, this is what your actionPerformed method should look like.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int n = cb.getSelectedIndex();
//etc
}
I have this code that writes an object:
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
And this code that loads the object:
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list.
Full source code:
import java.io.*;
import java.util.*;
public class Model implements java.io.Serializable {
private Student[] studentList = new Student[0];
private Module[] moduleList = new Module[0];
public void menu() {
while (true) {
System.out.println ("MENU");
System.out.println ("");
System.out.println (" 1 - Run Tests");
System.out.println (" 2 - Add Student");
System.out.println (" 3 - Add Module");
System.out.println (" 4 - Add Student To Module");
System.out.println (" 5 - Save System (Text file)");
System.out.println (" 6 - Load System (Text file)");
System.out.println (" 7 - Save System (Serialized)");
System.out.println (" 8 - Load System (Serialized)");
System.out.println (" 9 - Print Report");
System.out.println ("");
System.out.print ("Enter choice: ");
String input = keyboard.readString();
switch (input) {
case "1" :
runTests();
break;
case "2" :
System.out.print("First Name : ");
String fN = keyboard.readString();
System.out.print("Surname : ");
String sN = keyboard.readString();
System.out.print("Course Code : ");
String c = keyboard.readString();
System.out.print("User ID : ");
String iD = keyboard.readString();
AddStudent(iD, sN, fN, c);
break;
case "3" :
System.out.print("Module Code : ");
String code = keyboard.readString();
String[] temp = new String[0];
AddModule(code,temp);
break;
case "4" :
System.out.print("Module Code : ");
code = keyboard.readString();
Module m = findAModule(code);
if (m != null) {
System.out.print("User ID : ");
iD = keyboard.readString();
Student s = findAStudent(iD);
if (s != null) {
m.addThisStudent(s);
} else {
System.out.println("Student not found");
}
} else {
System.out.println("Module not found");
}
break;
case "5" :
saveToTextFiles();
break;
case "6" :
loadFromTextFiles();
break;
case "7" :
saveSerialized();
break;
case "8" :
break;
case "9" :
printReport();
break;
}
}
}
public void runTests() {
loadFromTextFiles();
saveSerialized();
printReport();
}
public void loadFromTextFiles() {
studentList = new Student[0];
moduleList = new Module[0];
try {
Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String u = fileReader.nextLine();
String sn = fileReader.nextLine();
String fn = fileReader.nextLine();
String c = fileReader.nextLine();
AddStudent(u, sn, fn, c);
}
fileReader.close();
fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String code = fileReader.nextLine();
int numOfStudents = fileReader.nextInt(); fileReader.nextLine();
String[] students = new String[numOfStudents];
for (int j = 0; j < numOfStudents; j++) {
students[j] = fileReader.nextLine();
}
AddModule(code, students);
}
fileReader.close();
} catch (IOException e) {}
}
public void saveToTextFiles () {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt")));
outfile.println(studentList.length);
for (int i = 0; i < studentList.length; i++) {
outfile.println(studentList[i].getUID());
outfile.println(studentList[i].getSN());
outfile.println(studentList[i].getFN());
outfile.println(studentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt")));
outfile.println(moduleList.length);
for (int i = 0; i < moduleList.length; i++) {
outfile.println(moduleList[i].getCode());
outfile.println(moduleList[i].getStudents().length);
for (int j = 0; j < moduleList[i].getStudents().length; j++) {
outfile.println(moduleList[i].getStudents()[j]);
}
}
outfile.close();
} catch (IOException e) {}
}
public void saveSerialized() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
FileOutputStream fileOut2 = new FileOutputStream("Module.ser");
ObjectOutputStream out2 = new ObjectOutputStream(fileOut2);
out2.writeObject(studentList);
out2.close();
fileOut2.close();
FileOutputStream fileOut3 = new FileOutputStream("Student.ser");
ObjectOutputStream out3 = new ObjectOutputStream(fileOut3);
out3.writeObject(moduleList);
out3.close();
fileOut3.close();
} catch (IOException e) {}
}
public void loadSerialized() {
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
private Module[] getModuleList() {
return moduleList;
}
private Student[] getStudentList() {
return studentList;
}
private void setModuleList(Module[] m) {
moduleList = m.clone();
}
private void setStudentList(Student[] s) {
studentList = s.clone();
}
private void AddModule(String code, String[] students) {
int length = moduleList.length;
Module NewArray[] = new Module[length + 1];
for (int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Module(moduleList[i]);
}
}
NewArray[length] = new Module(code, students);
moduleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = studentList.length;
Student NewArray[] = new Student[length + 1];
for(int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Student(studentList[i]);
}
}
NewArray[length] = new Student(u, sn, fn, c);
studentList = NewArray.clone();
}
public void printReport() {
for (int i = 0; i < moduleList.length; i++) {
System.out.println(moduleList[i].toString(this));
}
}
public Student findAStudent(String uid) {
for (int i = 0; i < studentList.length; i++) {
if (studentList[i].getUID().compareTo(uid) == 0) {
return studentList[i];
}
}
return null;
}
public Module findAModule(String code) {
for (int i = 0; i < moduleList.length; i++) {
if (moduleList[i].getCode().compareTo(code) == 0) {
return moduleList[i];
}
}
return null;
}
}
Look at your code sample, in particular the switch statement:
switch (input) {
...
case "8" :
break;
...
}
I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code.
Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module.
Edit: why using serialization to persist objects is a bad idea
In simple terms, using serialization to persist objects is brittle.
An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new.
While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system.
There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.