Johnathan Yaesu Johnathan Yaesu - 3 months ago 7
Java Question

How can I stop losing array data through separate method calls?

I am looking to make an array that can be used by multiple methods. I attempted this by creating a global array. But found out, that once the method that adds data to the array runs and terminates, the data is lost, and everything is null again.

The array is initialized here:

package book;

import book.BookIO;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
*
*
*/
public class UserInterface implements ActionListener {
int j=0;
int i;

//Containers
String hello;
JFrame frame = new JFrame("Java Program");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
//Buttons
JButton processItem = new JButton("Process Item #1");
JButton confirmItem = new JButton("Confirm Item #1");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//TextFields
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField("");
JTextField total = new JTextField();
//Labels
JLabel num = new JLabel("Enter Number of Items in this Order:");
JLabel bookID = new JLabel("Enter Book ID for Item #1:");
JLabel quantityItem = new JLabel("Enter Quantity for Item #1:");
JLabel itemInfo = new JLabel("Item #1:");
JLabel subtotal = new JLabel("Order subtotal for 0 Items(s):");
public String[] order = new String[i];
int k = 0;
public void startUI() {

UserInterface gui = new UserInterface();
gui.bookingUI();

}

public void bookingUI() {
//sets windows, and pane in the UI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);

//adding the labels to the panel
c.insets = new Insets(5, 0, 0, 0);
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo, c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal, c);
toppane.setBackground(Color.GREEN);
frame.add(toppane);

//add textfield to panel
c.ipadx = 400;
c.insets = new Insets(5, 10, 0, 0);
c.gridx = 3;
c.gridy = 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(quantity, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(total, c);

//----------------------------------------------------------BUTTOM PANE-------------------------
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.insets = new Insets(5, 5, 5, 5);
b.ipadx = 10;
b.ipady = 10;
b.gridx = 1;
b.gridy = 0;
bottomPane.add(processItem, b);
processItem.addActionListener(this);
b.gridx = 2;
b.gridy = 0;
bottomPane.add(confirmItem, b);
confirmItem.setEnabled(false);
confirmItem.addActionListener(this);
b.gridx = 3;
b.gridy = 0;
bottomPane.add(viewOrder, b);
viewOrder.setEnabled(true);
viewOrder.addActionListener(this);
b.gridx = 4;
b.gridy = 0;
bottomPane.add(finishOrder, b);
finishOrder.setEnabled(true);
finishOrder.addActionListener(this);
b.gridx = 5;
b.gridy = 0;
bottomPane.add(newOrder, b);
newOrder.addActionListener(this);
b.gridx = 6;
b.gridy = 0;
bottomPane.add(exit, b);
exit.addActionListener(this);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.setSize(810, 310);
frame.setVisible(true);
}

//action listener for the buttons
public void actionPerformed(ActionEvent e) {

int i = Integer.valueOf(amount.getText());
order = new String[i];

if (e.getSource() == processItem) {
processItem();

} else if (e.getSource() == confirmItem) {
confirmItem();
setProcessItemBtn();

} else if (e.getSource() == viewOrder) {
System.out.println(order.length);


} else if (e.getSource() == finishOrder) {

} else if (e.getSource() == newOrder) {
newOrder();
} else if (e.getSource() == exit) {
System.exit(0);
}
}

//Creating getters and setters to change the text for the buttons and labels, as well as getting text from the textfields.
public void setProcessItemBtn() {
processItem.setText("Process Item #");
processItem.validate();
processItem.repaint();
}

public void setConfirmItemBtn(int num) {
confirmItem.setText("Confirm Item #" + num);
confirmItem.validate();
confirmItem.repaint();
}

public void setViewOrderBtn(String title) {

viewOrder.validate();
viewOrder.repaint();
}

public void setInfo(String title, String price) {

info.setText(title + " " + price);
info.validate();
info.repaint();

}

public String getAmount() {
String str = amount.getText();
return str;
}
public void confirmItem(){
i = Integer.valueOf(amount.getText());
int amountOrdered = Integer.valueOf(quantity.getText());
System.out.println(k);



for (k = 0; k < amountOrdered; k++){
order[j] = id.getText() + " " + info.getText();

j++;

}
System.out.println(order[2]);
System.out.println(k);
if ((i-1)<j){
processItem.setEnabled(false);
confirmItem.setEnabled(false);

}else{
processItem.setEnabled(true);
confirmItem.setEnabled(false);
}



}
public void processItem(){
boolean ifFound = false;


confirmItem.setEnabled(true);
processItem.setEnabled(false);
BookIO findInfo = new BookIO();
ifFound = findInfo.readFile(id.getText(), this);

if (ifFound == true)
JOptionPane.showMessageDialog(null, "Found it");
else {
JOptionPane.showMessageDialog(null, "Book ID " + id.getText() + " not found in file");
confirmItem.setEnabled(false);
processItem.setEnabled(true);
}
}
public void newOrder(){

amount.setText(" ");
id.setText(" ");
quantity.setText(" ");
info.setText(" ");
total.setText(" ");



}
}


The method (confirmItem) basically takes in user information from text fields and stores it into an array to be later printed onto a message box, which will be in another method,that is activated from a separate event. This method is called multiple times through out the programs life to get additional information from the same textfields (it is the same related information). But when called, the data from the last method call is not present in the array. It is simply null.

Is there a way to keep data in an array without losing it through separate method calls? This array is also used by another method that hosts the same issue.

Thank you.

Answer

Every time you press any button in the UI, the actionPerformed method executes this line:

order = new String[i];

What that is doing is creating a new, blank array of length i and setting the order variable to point at the new blank array, so that the old array will be lost. If you want to expand an array, you must copy the contents of the old array into the new one:

String[] newOrder = new String[newLength];
System.arraycopy(order, 0, newOrder, 0, order.length);
order = newOrder;

Arrays.copyOf is a standard, easy way to do this in one line:

order = java.util.Arrays.copyOf(order, order.length + 1); // increase array length by 1

A List would also make this sort of thing easier than a bare array, because then you could just do: orders.add(someNewOrder); and it would expand the size automatically.

In any case, it's probably not something you want to do unconditionally every time any button is clicked. I'm not sure exactly how you intend the program to behave though.

Comments