Converting a program to use arrays INSTEAD of ArrayLists - java

I have a class ShoppingCart that utilizes ArrayList methods to carry out the program which is basically a program where you add groceries to your cart and such. However, I want to use arrays to do the program instead of ArrayLists since I want to work on my array knowledge. Here is the ShoppingCart class
import java.util.*;
#SuppressWarnings("serial")
public class ShoppingCart extends ArrayList<Selections> {
// FIELDS
private boolean discount;
// Selections[]......
// CONSTRUCTOR
public ShoppingCart() {
super();
discount = false;
}
// Adding to the Collection
public boolean add(Selections next) {
// check to see if it's already here
for (int i = 0; i < this.size(); i++)
if (get(i).equals(next)) {
set(i, next); // replace it
return true;
}
super.add(next); // add new to the array
return false;
}
// The GUI only know if check is on or off
public void setDiscount(boolean disc) {
discount = disc; // match discount from GUI
}
// total of selections
public double getTotal() {
double sum = 0.0;
for (int i = 0; i < this.size(); i++)
sum += get(i).priceFor();
if (discount) sum *= 0.9;
return sum;
}
}
The Selections class that is being used for the individual groceries.
import java.text.*;
// W.P. Iverson, instructor
// January 2018 for CS211
// Class that combines Item and ItemOrder
public class Selections {
// FIELDS
private String name; // friendly name
private double price; // cost of one
private int bulkQuantity; // when bulk price kicks in
private double bulkPrice; // price for the bulk quantity
private int quantity; // how many we are buying
private boolean hasBulk; // internally used
private NumberFormat curr; // for nice $12.34 currency formatting
// CONSTRUCTORS
public Selections(String name, double price) {
this(name, price, -99999, 99999.); // flag that nothing is selected with 99999
}
public Selections(String thing, double amount, int qty, double bulk) {
name = thing;
price = amount;
if (qty > 0) hasBulk = true;
bulkQuantity = qty;
bulkPrice = bulk;
quantity = 0; // starts with zero selected by user, GUI changes it later
curr = NumberFormat.getCurrencyInstance();
}
// decides how many we're buying
public void setQuantity(int number) {
quantity = number;
}
// calculates the price for this quantity
public double priceFor() {
if (hasBulk && quantity >= bulkQuantity)
return quantity / bulkQuantity * bulkPrice + quantity % bulkQuantity * price;
else
return quantity * price;
}
// basic output for console or GUI text
public String toString() {
if (hasBulk)
return name + ", " + curr.format(price) + " (" + bulkQuantity + " for " + curr.format(bulkPrice) + ")";
else
return name + ", " + curr.format(price);
}
}
I made a JFrame for the program already but just want to get it to use regular arrays instead! Thanks for your help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
#SuppressWarnings("serial")
public class ShoppingFrame extends JFrame {
private ShoppingCart items;
private JTextField total;
public ShoppingFrame(Selections[] array) {
// create frame and order list
setTitle("CS211 Shopping List");
setDefaultCloseOperation(EXIT_ON_CLOSE);
items = new ShoppingCart();
// set up text field with order total
total = new JTextField("$0.00", 12);
total.setEditable(false);
total.setEnabled(false);
total.setDisabledTextColor(Color.BLACK);
JPanel p = new JPanel();
p.setBackground(Color.blue);
JLabel l = new JLabel("order total");
l.setForeground(Color.YELLOW);
p.add(l);
p.add(total);
add(p, BorderLayout.NORTH);
p = new JPanel(new GridLayout(array.length, 1));
for (int i = 0; i < array.length; i++)
addItem(array[i], p);
add(p, BorderLayout.CENTER);
p = new JPanel();
add(makeCheckBoxPanel(), BorderLayout.SOUTH);
// adjust size to just fit
pack();
}
// Sets up the "discount" checkbox for the frame
private JPanel makeCheckBoxPanel() {
JPanel p = new JPanel();
p.setBackground(Color.blue);
final JCheckBox cb = new JCheckBox("qualify for discount");
p.add(cb);
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
items.setDiscount(cb.isSelected());
updateTotal();
}
});
return p;
}
// adds a product to the panel, including a textfield for user input of
// the quantity
private void addItem(final Selections product, JPanel p) {
JPanel sub = new JPanel(new FlowLayout(FlowLayout.LEFT));
sub.setBackground(new Color(0, 180, 0));
final JTextField quantity = new JTextField(3);
quantity.setHorizontalAlignment(SwingConstants.CENTER);
quantity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateItem(product, quantity);
quantity.transferFocus();
}
});
quantity.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
updateItem(product, quantity);
}
});
sub.add(quantity);
JLabel l = new JLabel("" + product);
l.setForeground(Color.white);
sub.add(l);
p.add(sub);
}
// When the user types a new value into one of the quantity fields,
// parse the input and update the ShoppingCart. Display an error
// message if text is not a number or is negative.
private void updateItem(Selections product, JTextField quantity) {
int number;
String text = quantity.getText().trim();
try {
number = Integer.parseInt(text);
} catch (NumberFormatException error) {
number = 0;
}
if (number <= 0 && text.length() > 0) {
Toolkit.getDefaultToolkit().beep();
quantity.setText("");
number = 0;
}
product.setQuantity(number);
items.add(product);
updateTotal();
}
// reset the text field for order total
private void updateTotal() {
double amount = items.getTotal();
total.setText(NumberFormat.getCurrencyInstance().format(amount));
}
public static void main(String[] args) {
Selections[] array = new Selections[10];
array[0] = new Selections("silly putty", 3.95, 10, 19.99);
array[1] = new Selections("silly string", 3.50, 10, 14.95);
array[2] = new Selections("bottle o bubbles", 0.99);
array[3] = new Selections("Nintendo Wii system", 389.99);
array[4] = new Selections("Mario Computer Science Party 2 (Wii)", 49.99);
array[5] = new Selections("Don Knuth Code Jam Challenge (Wii)", 49.99);
array[6] = new Selections("Computer Science pen", 3.40);
array[7] = new Selections("Rubik's cube", 9.10);
array[8] = new Selections("Computer Science Barbie", 19.99);
array[9] = new Selections("'Java Rules!' button", 0.99, 10, 5.0);
ShoppingFrame f = new ShoppingFrame(array);
f.setVisible(true);
}
}

You can use an array member variable in ShoppingCart class like this:
private Selections[] selectionsArray;
instead of extending ArrayList<Selections>. (Then you will have to handle resizing the array yourself.)

Related

Main method in different class can't detect button press

I'm making a program for practice and it's basically simulating winning/losing Powerball tickets. Anyways, the main class is in launchPowerBall.java and the button that I am trying to detect when clicked is in PowerBallGUI.java. The button works by itself, however, the main in launchPowerBall.java isn't able to detect it even though I set up myself a few setters and getters. Any clue what alternative I can do instead? Because it seems as though even though I run it through a while(true) loop and I keep pressing the button, there seems to be no detection from the main method.
Here's the action listener for the JButton:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
Here's what I'm trying to do for the main method:
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
}
Here's the three files if you need to see my code:
1) https://gist.github.com/anonymous/e5950413470202cd1ac6d24e238ff693
2) https://gist.github.com/anonymous/773e4e4454a79c057da78eed038fade1
3) https://gist.github.com/anonymous/82335e634c1f84607d3021b4d683cc65
Powerball...
public class PowerBall {
private int[] numbers = {0, 0, 0, 0, 0};
private int[] lotteryNumbers = {0, 0, 0, 0, 0};
private int powerBall;
private int lotteryPowerBall;
private double balance;
private double winnings;
/*** Constructor Methods ***/
public PowerBall() {
powerBall = 0;
balance = 1000;
winnings = 0;
}
/*** Mutator Methods ***/
public void randomize() {
int i;
int highestNumber = 59;
int highestPowerball = 32;
int temp = 0;
for (i = 0; i < numbers.length; i++) {
// Choose a random number
temp = (int)(Math.random() * highestNumber);
numbers[i] = temp;
}
// Choose a random Powerball number
powerBall = (int)(Math.random() * highestPowerball);
// Choose the lottery numbers
for (i = 0; i < lotteryNumbers.length; i++) {
temp = (int)(Math.random() * highestNumber);
lotteryNumbers[i] = temp;
}
lotteryPowerBall = (int)(Math.random() * highestPowerball);
}
public void calculate() {
int matches = 0;
int powerballMatches = 0;
if (balance > 0) {
// Check to see if there are any matches between the two sets of numbers
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < lotteryNumbers.length; j++) {
if (numbers[i] == lotteryNumbers[j]) {
matches++;
}
}
}
// Check to see if the two different powerball numbers match
if (powerBall == lotteryPowerBall) {
powerballMatches = 1;
}
// Calculate the balance/winnings if there were any matches
if (matches == 0 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 0 && powerballMatches == 1) {
balance = balance + 4;
winnings = winnings + 4;
} else if (matches == 0 && powerballMatches == 0 || matches == 1 && powerballMatches == 0) {
balance = balance - 2;
winnings = winnings - 2;
} else if (matches == 2 && powerballMatches == 1) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 0) {
balance = balance + 7;
winnings = winnings + 7;
} else if (matches == 3 && powerballMatches == 1) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 0) {
balance = balance + 100;
winnings = winnings + 100;
} else if (matches == 4 && powerballMatches == 1) {
balance = balance + 50000;
winnings = winnings + 50000;
} else if (matches == 5 && powerballMatches == 0) {
balance = balance + 1000000;
winnings = winnings + 1000000;
} else if (matches == 5 && powerballMatches == 1) {
balance = balance + 10000000;
winnings = winnings + 10000000;
}
//System.out.println("There is currently " + matches + " number matches.");
//System.out.println("There is currently " + powerballMatches + " powerball number matches.\n");
} else {
System.out.println("YOU ARE BROKE!");
}
}
/*** Accessor/Observor Methods ***/
public void displayBalance() {
System.out.print("Your balance is at: $");
System.out.printf("%.2f", balance);
}
public void displayWinnings() {
System.out.print("\nYou have currently won: $");
System.out.printf("%.2f", winnings);
System.out.println("\n");
}
public String toString() {
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
if (numbers.length == lotteryNumbers.length) {
for (int i = 0; i < numbers.length; i++) {
if (i < numbers.length - 1) {
builder.append(numbers[i] + ", ");
builder2.append(lotteryNumbers[i] + ", ");
} else {
builder.append(numbers[i] + " + ");
builder2.append(lotteryNumbers[i] + " + ");
}
}
} else {
return "ERROR: Numbers max set of numbers doesn't match Lottery Numbers max set of numbers!\n";
}
return "Your set of numbers were: " + builder + Integer.toString(powerBall) +
"\nThe powerball numbers were: " + builder2 + lotteryPowerBall;
}
}
Launcher
public class launchPowerBall {
public static void main(String[] args) throws InterruptedException {
// Build the GUI object
PowerBallGUI GUI = new PowerBallGUI();
GUI.buildGUI();
//GUI.setTextArea("banana");
// Build the PowerBall object
PowerBall roll = new PowerBall();
while(true) {
if (GUI.getJButton().getModel().isPressed()) {
System.out.println("TEST");
}
}
//System.out.println("TOO LATE!");
//while (true) {
/*roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
Thread.sleep(500); */
//}
}
}
GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PowerBallGUI {
private JButton start = new JButton("Launch the Powerball!");
private boolean buttonPressed = false;
private String outText;
/*** Constructor Methods ***/
public PowerBallGUI() {
#SuppressWarnings("unused")
JTextArea outputText = new JTextArea("Press the 'Launch the Powerball' button to start!");
}
/*** Setters ***/
/*** Sets the JTextArea object ***/
public void setTextArea (String str) {
this.outText = str;
}
public void setButtonPressed (Boolean bool) {
this.buttonPressed = bool;
}
/*** Getters ***/
public Boolean getButtonPressed() {
return this.buttonPressed;
}
public JButton getJButton() {
return this.start;
}
/*** Builds the GUI ***/
public void buildGUI() {
// Create the Java Frame itself
JFrame frame = new JFrame("Can YOU win the Powerball? v1.0 (Programmed by: Josh Yang)");
// Sets the default close operation of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the size of the frame
frame.setSize(800, 500);
// Sets the location of the frame
centerGUI(frame);
// Allows the frame to be seen
frame.setVisible(true);
// Disables frame resizing
//frame.setResizable(false);
// Create the Java Panel itself
JPanel panel = new JPanel();
JPanel contentPanel = new JPanel();
JPanel launchPanel = new JPanel();
// Sets the sides of the Java panels
panel.setSize(800, 150);
// Set the panel background color
panel.setBackground(Color.YELLOW);
contentPanel.setBackground(Color.YELLOW);
launchPanel.setBackground(Color.PINK);
// Add the panel onto the frame
frame.add(panel, "North");
frame.add(contentPanel, BorderLayout.CENTER);
frame.add(launchPanel, BorderLayout.SOUTH);
// Set top panel's preferred size dimensions
panel.setPreferredSize(new Dimension(800, 100));
// Adds components onto the panel
JLabel title = new JLabel("Can YOU win the lottery? v1.0", SwingConstants.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 25));
panel.add(title);
String text = "Basically, we start you off at $1000 and buy tickets in increments of $2 until you win big (if you do, that is)!";
JLabel description = new JLabel();
description.setText(text);
description.setFont(new Font("Serif", Font.PLAIN, 16));
panel.add(description);
// ContentPanel area
JLabel cDescription = new JLabel("Output: ");
contentPanel.add(cDescription);
JTextArea outputText = new JTextArea(17, 60);
outputText.setBackground(Color.PINK);
outputText.setEditable(false);
outputText.setText("Press the 'Launch the Powerball' button to start!");
contentPanel.add(outputText);
start.setLocation(100, 100);
launchPanel.add(start);
// Add an action listener to the JButton
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
frame.revalidate();
//frame.pack();
}
/*** Centers the GUI based on screen size ***/
public static void centerGUI(Window frame) {
// Gets the size of the screen
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
// Set the frame location based on x and y
frame.setLocation(x, y);
}
}
The simple solution is to take the functionality you're "trying" to execute in the main method and put in the ActionListener...
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// If the button is pressed, delete text field and replace with new content
PowerBall roll = new PowerBall();
roll.randomize();
System.out.println(roll.toString());
roll.calculate();
roll.displayBalance();
roll.displayWinnings();
setButtonPressed(true);
outputText.setText("");
outputText.setText(outText);
}
});
If you "really" want to do more work in the main, you will need to generate some kind of observer pattern which can notified when something occurs.
You could put one on Powerball so it could notify you of a status change or on the GUI which notify you that the start button was pressed

NullPointerException when attempting to insert items into array from JDialog box

As it states, when I attempt to insert an item into an object array via my JDialog popup, I get a NullPointerException. I reworked an existing app to create the JDialog, which opens from another application class currently named Project6(). The JDialog class, called ProcessRec(), worked fine when it ran as a standalone GUI(before I made it a JDialog).
My stacktrace is rather unhelpful in this case, as it only points to the method that is attempting to insert data into the array(which, like I said, worked fine before) and the GUI buttons that correspond to them.
The constructor for ProcessRec() accepts a ToolWarehouse() object, which matches the class that creates my object array(which is an array of objects from another class I have defined, ToolItem() ).
public ProcessRec(ToolWarehouse tools)
When it ran on it's own, ProcessRec() constructor params were empty(default).
When ProcessRec() ran as a standalone GUI for inputting data into the array, I would create an object using the default constructor like so:
ToolWareHouse tools = new ToolWarehouse();
and I would then use it's method insert() to enter data into the array.
Now that it is a JDialog, though, I was instructed to change to:
ToolWarehouse tools;
However this causes the NullPointerException because, and i'm guessing, the compiler is pointing to an object that doesn't exist. When I create a new object in ProcessRec(), as I did when it was a standalone, I no longer get this exception. However, when I attempt to store data into the array using insert(), it does not work and the data cannot be found(although I receive a prompt saying the insert was successful).
I know very little about instances of classes, but i'm assuming that the reason my data isn't showing is because it is using a whole different instance of the ToolWarehouse() class? Is the format:
public ProcessRec(ToolWarehouse tools)
accepting the same instance of the class used before? I may be way off base here, so I was hoping someone could help me understand what may be happening and why.
If more info is needed I apologize, i'll add whatever is necessary. The code is somewhat lengthy and I didn't want to take up space. Thanks a ton.
EDIT: Here is the ProcessRec() class, which creates the JDialog box, along with some of the methods corresponding to it's use.
public class ProcessRec extends JDialog
{
//global declarations
private JButton insertBtn;
private JButton deleteBtn;
private JButton displayBtn;
private JButton hideBtn;
private JButton clearBtn;
private JTextField toolFld;
private JTextField idFld;
private JTextField priceFld;
private JTextField qualityFld;
private JTextField numInStockFld;
private JTextField messageFld;
private JLabel messageLbl;
private Font f1 = new Font("serif", Font.BOLD, 24);
private Font f2 = new Font("serif", Font.PLAIN, 18);
private Container c = getContentPane();
private String input = "";
private String toolInput = "";
private int responseCode = 0;
private int idInput = 0;
private int qualityInput = 0;
private int numInStockInput = 0;
private double priceInput = 0.0;
private ToolWarehouse tools = new ToolWarehouse();
//constructor for GUI elements and event listeners
public ProcessRec(ToolWarehouse tools)
{
setTitle("Project1");
setSize(520,450);
c.setLayout(new FlowLayout());
JLabel title = new JLabel("Tiny Tim's Tool Warehouse, Inc.");
title.setFont(f1);
c.add(title);
JTextField toolLbl = new JTextField("Enter tool name:", 15);
toolLbl.setEditable(false);
c.add(toolLbl);
toolFld = new JTextField(25);
c.add(toolFld);
JTextField idLbl = new JTextField("Enter ID:", 15);
idLbl.setEditable(false);
c.add(idLbl);
idFld = new JTextField(25);
c.add(idFld);
JTextField priceLbl = new JTextField("Base Price:", 15);
priceLbl.setEditable(false);
c.add(priceLbl);
priceFld = new JTextField(25);
c.add(priceFld);
JTextField qualityLbl = new JTextField("Enter Quality:", 15);
qualityLbl.setEditable(false);
c.add(qualityLbl);
qualityFld = new JTextField(25);
c.add(qualityFld);
JTextField numInStockLbl = new JTextField("Enter Number in Stock:", 15);
numInStockLbl.setEditable(false);
c.add(numInStockLbl);
numInStockFld = new JTextField(25);
c.add(numInStockFld);
insertBtn = new JButton("Insert");
c.add(insertBtn);
deleteBtn = new JButton("Delete");
c.add(deleteBtn);
displayBtn = new JButton("Display");
c.add(displayBtn);
hideBtn = new JButton("Hide");
c.add(hideBtn);
clearBtn = new JButton("Clear");
c.add(clearBtn);
JLabel messageLbl = new JLabel("Messages:");
messageLbl.setFont(f2);
c.add(messageLbl);
messageFld = new JTextField(30);
c.add(messageFld);
//button listeners
insertBtn.addActionListener(new EventListener());
deleteBtn.addActionListener(new EventListener());
displayBtn.addActionListener(new EventListener());
hideBtn.addActionListener(new EventListener());
clearBtn.addActionListener(new EventListener());
} //end constructor
public String getToolRecords(int index)
{
return tools.getRecord(index);
}
public int getNumberOfItems()
{
return tools.getNumberOfItems();
}
//Action Listener
private class EventListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource() == insertBtn)
{
toolInput = toolFld.getText();
input = idFld.getText();
idInput = Integer.parseInt(input);
input = priceFld.getText();
priceInput = Double.parseDouble(input);
input = qualityFld.getText();
qualityInput = Integer.parseInt(input);
input = numInStockFld.getText();
numInStockInput = Integer.parseInt(input);
responseCode = tools.insert(qualityInput, toolInput, idInput, numInStockInput,
priceInput);
if (responseCode == 1)
{
messageFld.setText(idInput + " - Successful insertion");
}
else if (responseCode == 0)
{
messageFld.setText(idInput + " - Array is full");
}
else if (responseCode == -1)
{
messageFld.setText(idInput + " - Duplicate/Invalid ID");
}
if (tools.getNumberOfItems() < 10)
{
JOptionPane.showMessageDialog(null, "Tool Name: " + toolInput
+ "\nTool ID: " + idInput + "\nTool Base Price: " + "$" + priceInput
+ "\nQuality: " + qualityInput + "\nNumber In Stock: "
+ numInStockInput, "Insert Review", JOptionPane.INFORMATION_MESSAGE);
}
else if (tools.getNumberOfItems() == 10)
{
JOptionPane.showMessageDialog(null, "The array is full, please delete an entry",
"Insert Review", JOptionPane.INFORMATION_MESSAGE);
}
}//end insert button
else if (ev.getSource() == deleteBtn)
{
input = idFld.getText();
idInput = Integer.parseInt(input);
responseCode = tools.delete(idInput);
if (responseCode == 1)
{
messageFld.setText(idInput + " - Successful deletion");
}
else if (responseCode == -1)
{
messageFld.setText(idInput + " - ID not found");
}
}//end delete button
else if (ev.getSource() == displayBtn)
{
tools.display();
}
else if (ev.getSource() == hideBtn)
{
//setState(JFrame.ICONIFIED);
}
else if (ev.getSource() == clearBtn)
{
qualityFld.setText(null);
toolFld.setText(null);
idFld.setText(null);
numInStockFld.setText(null);
priceFld.setText(null);
messageFld.setText(null);
repaint();
}//end clear button
}//end actionPerformed
}//end ActionListener
}//end Project1
ToolWarehouse class that creates the array:
public class ToolWarehouse
{
//Global declarations
private int numberOfItems = 0;
private int index = 0;
private int returnCode = 0;
protected ToolItem[] toolArray = new ToolItem[10];
public ToolWarehouse()
{
numberOfItems = 0;
//creating the array of ToolItems
for (int i = 0; i < toolArray.length; i++)
{
toolArray[i] = new ToolItem();
System.out.println(toolArray[i]);
}
}//end constructor
public int searchArray(int id)
{
for (index = 0; index < toolArray.length; index++)
{
if (toolArray[index].getToolID() == id)
{
System.out.println("ID found at location " + index);
return index;
}
}
return -1;
}//end searchArray
public int insert(int quality, String name, int id, int numInStock, double price)
{
returnCode = searchArray(id);
if (numberOfItems == 10)
{
System.out.println("Array is full");
return 0;
}
else if (returnCode == -1)
{
boolean oK = toolArray[numberOfItems].assign(quality, name, id, numInStock,
price);
if (oK == true)
{
System.out.println("Successful insertion");
numberOfItems++;
return 1;
}
}
return -1;
}//end insert
public int delete(int ID)
{
returnCode = searchArray(ID);
if (returnCode != -1)
{
toolArray[returnCode] = new ToolItem();
for (index = returnCode; index < numberOfItems; index++)
{
toolArray[index] = toolArray[index + 1];
}
numberOfItems--;
System.out.println("Successful deletion");
return 1;
}
else
System.out.println("ID not found");
return -1;
}//end delete
public void display()
{
for (index = 0; index < numberOfItems; index++)
{
toolArray[index].calcAdjustedPrice();
toolArray[index].display();
}
}//end display
public String getRecord(int index)
{
return "Tool Name: " + toolArray[index].getName()
+ "| Tool ID: " + toolArray[index].getToolID()
+ "| Tool Quality: " + toolArray[index].getQuality()
+ "| Number in Stock: " + toolArray[index].getNumberInStock()
+ "| Tool Price: " + toolArray[index].getPrice();
}//end getRecord
public int getNumberOfItems()
{
return numberOfItems;
}
}//end ToolWarehouse
And the current portion i'm working on now, which calls insert() from the ToolWarehouse() class, but does not properly insert into the array i'm working on when creating an object of the ToolWarehouse() class using default constructor(even though my println debugging statements indicate it does):
public void readBSAFile() throws IOException,
FileNotFoundException
{
FileInputStream fstream2 = new FileInputStream(filename);
DataInputStream dstream2 = new DataInputStream(fstream2);
while (dstream2.available() > 0)
{
try
{
toolName = dstream2.readUTF();
id = dstream2.readInt();
quality = dstream2.readInt();
numInStock = dstream2.readInt();
price = dstream2.readDouble();
dstream2.close();
System.out.println(toolName);
System.out.println(id);
System.out.println(quality);
System.out.println(numInStock);
System.out.println(price);
//tools.insert(quality, toolName, id, numInStock, price);
}
catch (EOFException e)
{
System.out.println("End of file reached");
}
}
tools.insert(quality, toolName, id, numInStock, price);
}//end readBSAFile
Indeed, you have to make sure the object is initialized before attempting to use it. You put
ToolWarehouse tools;
as a class variable, and in the dialog method you could say
tools = new ToolWareHouse();
to create the object and start using it. But maybe a better way is to just initialize it as a class variable straight way. e.g write
ToolWarehouse tools = new ToolWareHouse();
at the top of the class. (So it's a class variable, and known throughout the whole class)
You didn't show us too much code, so it's hard to tell what the exact problem is. But as you said, you don't initialize your object, so you're bound to get a nullPointerException when trying to pass it on to another method & use it.

NumberFormatException: empty string when clicking the JButton?

I made a program that has a JFrame that contains a JTextField, a button, and two JLabels. When a number is typed into the JTextField, either pressing the enter key or clicking on the JButton should display the number in scientific notation on the second JLabel. When I hit the enter key, it works, however, when I click on the JButton, it does not. It gives me a NumberFormatException: empty string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyMath extends JPanel implements ActionListener
{
private JTextField textField;
private static JLabel textArea;
private static JLabel comment;
private JButton button;
private static JFrame frame;
public MyMath()
{
comment = new JLabel("Enter a number");
textField = new JTextField();
textField.setSize(new Dimension(10 , 10));
textField.addActionListener(this);
button = new JButton("Go");
button.addActionListener(this);
}
public static void addComponentsToPane(Container pane)
{
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField);
pane.add(new MyMath().button);
pane.add(new MyMath().comment);
pane.add(textArea);
}
public void actionPerformed(ActionEvent evt)
{
String text = textField.getText();
textArea.setText(SciNotation.convertToSciNotation(text));
textArea.setHorizontalAlignment(SwingConstants.CENTER);
comment.setText(text + " in Scientific Notation:");
textField.selectAll();
}
private static void createAndShowGUI()
{
frame = new JFrame("Scientific Notation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
Container bg = frame.getContentPane();
Dimension d = new Dimension(300, 150);
bg.setPreferredSize(d);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GREEN);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Point screenCenter = new Point (screen.width/2 , screen.height/2);
Point center = new Point(screenCenter.x - (150), screenCenter.y - (75));
frame.setLocation(center);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Here is SciNotation.java
import java.awt.Component;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
public class SciNotation
{
public static String convertToSciNotation(String num)
{
num = num.replaceAll("," , "");
if (num.contains("E")) //not working
{
String[] partsE = num.split("E");
String beforeE = partsE[0];
String afterE = partsE[1];
char first = num.charAt(0);
num = first + beforeE;
}
double number = Double.parseDouble(num);
double resultNumber = 0;
int power = 0;
String numString = Double.toString(number);
String[] parts = numString.split("\\.");
String decimals = parts[1];
int decimalInt = Integer.parseInt(decimals);
int numberInt = (int) number;
if(number > -1 && number < 1)
{
String[] low = numString.split("\\.");
String afterLow = low[1];
for(int i = 1; i < 10; i++)
{
String decNums = Integer.toString(i);
afterLow = afterLow.replaceAll(decNums, "");
int zeros = afterLow.length();
power = -1 * (zeros + 1);
resultNumber = number * Math.pow(10, zeros + 1);
decimals = "";
}
}
if(decimalInt == 0)
{
decimals = "";
}
if( number >= 10)
{
power = Integer.toString(numberInt).length() - 1;
resultNumber = numberInt/(Math.pow(10,(power)));
}
if((number >= 1 && number < 10) || (number <= -1 && number > -10))
{
resultNumber = number;
decimals = "";
}
if(number <= -10)
{
power = Integer.toString(numberInt).length() - 2;
resultNumber = numberInt/(Math.pow(10,(power)));
}
return resultNumber + decimals + " x 10^" + power;
}
}
This bug is pretty tricky. You constructed three MyMath instances. So your code was holding a wrong reference to your JTextFiled instance. That's why you couldn't get the right input.
public static void addComponentsToPane(Container pane) {
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(new MyMath().textField); //MyMath instance 1
pane.add(new MyMath().button); //MyMath instance 2
pane.add(new MyMath().comment); //MyMath instance 3
pane.add(textArea);
}
Here is the right code:
public static void addComponentsToPane(Container pane) {
MyMath myMath = new MyMath();
textArea = new JLabel(" ");
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.add(myMath.textField);
pane.add(myMath.button);
pane.add(myMath.comment);
pane.add(textArea);
}
:)

*new title: JButton array scope (it was:change color of button with button name)

How can is alter the color of the correct button?
It is for a small application, this app has 5 buttons from a array.(the name's are a,b,c,d,e)
The appearence of the buttons have to alter (change color) when i type in a number in a Jtextfield.
I added a name to each button:
knop = new JButton(Titel[i]);
knop.setName(tel[i]);
Here i get the text:
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke-1 >0 && welke-1<5)
{
vraag.setText("Goeie keus!");
if (welke == 1){
knop.setBackground(Color.BLUE);
}
knop.setBackground(Color.red);
}
But now it only changes the last button to red which is created bij the array.
So the question can I select a button by its name?
So if (input = 1) alter button 1 to green. in stead of only button 5.
I have tried de solution of gile, but i can't get it to work:
I get every time a: "AWT-EventQueue-0" java.lang.NullPointerException"
package kiesknop;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//public class Paneel extends JApplet
public class Paneel extends JFrame
{
private JPanel paneel;
private JButton knop;
public JTextField antwoord;
private JLabel vraag;
public JButton[] knops;
public Paneel() {
int [][] numButtons = new int [5][4];
numButtons[0][0] = 50;
numButtons[0][1] = 10;
numButtons[0][2] = 10;
numButtons[0][3] = 10;
numButtons[1][0] = 100;
numButtons[1][1] = 10;
numButtons[1][2] = 30;
numButtons[1][3] = 30;
numButtons[2][0] = 200;
numButtons[2][1] = 10;
numButtons[2][2] = 50;
numButtons[2][3] = 50;
numButtons[3][0] = 300;
numButtons[3][1] = 10;
numButtons[3][2] = 100;
numButtons[3][3] = 100;
numButtons[4][0] = 500;
numButtons[4][1] = 10;
numButtons[4][2] = 200;
numButtons[4][3] = 200;
String [] Titel = new String [5];
Titel [0] = "*";
Titel [1] = "**";
Titel [2] = "***";
Titel [3] = "****";
Titel [4] = "*****";
String [] tel = new String [5];
tel [0] = "a";
tel [1] = "b";
tel [2] = "c";
tel [3] = "d";
tel [4] = "e";
paneel = new JPanel();
JButton[] knops = new JButton[5];
for (int i = 0; i < 5; i++)
{
knops[i] = new JButton(Titel[i]);
knops[i].setName (tel[i]);
knops[i].setBounds(numButtons[i][0],numButtons[i][1], numButtons[i][2], numButtons[i][3]);
knops[i].addActionListener(new KnopHandler());
}
for (int i = 0; i < 5; i++)
{
paneel.add(knops[i]);
}
vraag = new JLabel("Welke knop grootte vind je het mooist?");
vraag.setBounds(100, 400, 250, 20);
antwoord = new JTextField(20);
antwoord.setBounds(500, 400, 100, 20);
antwoord.setEditable(true);
antwoord.addActionListener(new AntwoordHandler());
paneel.add (vraag);
paneel.add (antwoord);
setContentPane (paneel);
}
public class KnopHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton o = (JButton)e.getSource();
String Text = o.getText();
String name = o.getName();
String Label =o.getLabel();
System.out.println("knop gedrukt");
System.out.println(Text);
System.out.println(name);
System.out.println(Label);
}
}
class AntwoordHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String invoer = antwoord.getText();
try
{
int welke = Integer.parseInt(invoer);
if (welke >0 && welke<5)
{
vraag.setText("Goeie keus!");
if(welke == 1)// knops[welke].setBackground(Color.BLUE);
System.out.println(knops[1]);
if(welke == 2) knops[welke].setBackground(Color.BLUE);
if(welke == 3) knops[welke].setBackground(Color.BLUE);
if(welke == 4) knops[welke].setBackground(Color.BLUE);
if(welke == 5) knops[welke].setBackground(Color.BLUE);
}
else vraag.setText("Geen geldige invoer!");
}
catch( NumberFormatException nfe)
{
if( invoer.equals("")) vraag.setText("Niets ingevuld!");
else
vraag.setText("Alleen nummers invoeren!");
}
}
}
public static void main (String arg[])
{
JFrame frame = new Paneel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);
frame.setSize(900, 500);
}
}
What am i doing wrong ?
You can put buttons in an array
JButton[] knops = new JButton[5];
...
knops[i] = new JButton(Titel[i]);
...
And then set the background after user entered a number:
if (welke == 1){
knops[welke].setBackground(Color.GREEN);
}
Your title doesn't match with the given example: you are asking to get a button reference with string name but you are trying to parse the name to an integer.
However, if i understood your requirement correctly: I can think of two option:
Traverse each button of the button's array you have and compare with their name with your target name: you can get the name of the component(JButton) invoking button.getName().
Instead of using array which require traverse each time to get the target button with matching name, Create a HashMap<key, value>: HashMap<String, JButton>, map the button to their name and use it to get the component on Action Event.
HashMap<String, JButton>buttomMap = new HashMap<>();
buttonMap.put("kicker", kickerButton); // kickButton is a button
//// Then in actionPerformed() function
JButton button = buttonMap.get("kicker");
button.setBackground(Color.BLUE);

Java Sorting data from a file using JCheckboxes

I'm trying to create a program that will take data in from a random access file and sort it based on whichever checkbox the user selects. The data should be sorted by either the bank account number, customer name or balance (when a user clicks that checkbox the data in the text area becomes sorted based on that). Once the data is sorted, it is outputted into the JTextArea. I'm also trying to output the total amount of entries from the file in the text field below the check boxes.
Thanks!
import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;
public class GUIBankAcctSorter extends JFrame implements ItemListener {
public static void main(String[] args) {
GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
myFrame.setVisible(true);
Path file = Paths.get("C:\\Java\\Bank.txt");
final String ID_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final String EMPTY_ACCT = "0000";
String[] array = new String[3];
double balance = 0;
output(s, array, delimiter, balance, EMPTY_ACCT, file);
}
private static final long serialVersionUID = 1L;
private static final int WIDTH = 450;
private static final int HEIGHT = 310;
private static final int X_ORIGIN = 200;
private static final int Y_ORIGIN = 200;
JLabel title = new JLabel("Bank Account Sorter");
JLabel sort = new JLabel("Sort By ");
JLabel total = new JLabel("Total # of Bank Accounts ");
private Container con = getContentPane();
private FlowLayout layout = new FlowLayout();
static JTextArea area = new JTextArea(10, 35);
static JTextField field = new JTextField(5);
JCheckBox cust = new JCheckBox(" Cust # ", false);
JCheckBox bal = new JCheckBox(" Balance ", false);
JCheckBox name = new JCheckBox(" Name ", false);
public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){
String temp = "";
try{
InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
while(s != null){
array = s.split(delimiter);
if(!array[0].equals(EMPTY_ACCT)){
balance = Double.parseDouble(array[2]);
area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2] + "\n");
}
s = reader.readLine();
}
reader.close();
}catch(Exception e){
System.out.println("Message: " + e);
}
field.setText(temp);
}
public GUIBankAcctSorter(){
super("Bank Account Sorter");
Font headFont = new Font("Arial", Font.BOLD, 28);
con.setLayout(layout);
title.setFont(headFont);
con.add(title);
area.setEditable(false);
field.setEditable(false);
con.add(new JScrollPane(area));
cust.addItemListener(this);
bal.addItemListener(this);
name.addItemListener(this);
con.add(sort);
con.add(cust);
con.add(bal);
con.add(name);
con.add(total);
con.add(field);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == cust){
if(select == ItemEvent.SELECTED){
bal.setSelected(false);
name.setSelected(false);
}
}
if(source == bal){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
name.setSelected(false);
}
}
if(source == name){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
bal.setSelected(false);
}
}
}
}
Here you can see a good example using comparator to sort the object.
Let us suppose:
RowTest is a class that represent a single row of grid.
orderAMT is a class variable/Column/JTextField of Row.
Now the code below show how to sort the List of RowTest according to its attribute orderAMT.
List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
Comparator comparator = new OrderAMTComparator();
Collections.sort(sortedList, comparator);
public class OrderAMTComparator implements Comparator<RowTest> {
#Override
public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list
//repace getOrderAMT with other fields.
BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());
//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement
if (compareRes.compareTo(new BigDecimal(0)) == -1) {
return -1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
return 1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
return 0;
}
return compareRes.intValue();
}
}
I hope you have understand this. If not I will elaborate.
Thankyou.
Is there anyway to do it with checkboxes?
Certainly:
Declare an Account class that stores the account number, name & balance.
Add each new Account to a List structure such as ArrayList.
Create a Comparator relevant to each of the 2 fields.
At time of sort, use Collections.sort(list,comparator).
Refresh the text area with the content of the sorted list.
Other tips
Since those check boxes are mutually exclusive, they should really be a ButtonGroup of JRadioButton instances.
Change setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); & setLocationRelativeTo(null) to setLocationByPlatform(true). See this answer for a demo.
Change setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT); for pack() (& use layouts more effectively).

Categories