Issues with adding doubles in an ArrayList - java

I'm finishing up a GUI program that'll act as an online ordering menu for a restuarant, however I seem to be having two problems..
My calculate handler method seems to just freeze the entire java applet. It doesnt show any error or anything as well it just freezes. heres the event handler:
ArrayList<Double> yourOrderPrices = new ArrayList<Double>();
ArrayList<String>yourOrderName = new ArrayList<String>();
ArrayList<String> specifications = new ArrayList<String>();
Iterator<Double> it1 = yourOrderPrices.iterator();
private void calcButtonActionPerformed(java.awt.event.ActionEvent evt) {
int x = 0;
double temp;
while(it1.hasNext()){
temp = yourOrderPrices.get(x);
orderTotal += temp;
}
subTotalLabel.setText("Sub Total: " + orderTotal);
totalPriceLabel.setText("Tax Rate: " + orderTotal / TAX_RATE);
totalPriceLabel.setText("Total: " + (orderTotal / TAX_RATE) + orderTotal);
//Reset Variable
orderTotal = 0;
}
Basically what this is supposed to do is calculate the sub total by adding all of the prices in the yourOrderPrices ArrayList, its supposed to divide by the tax rate and display it, and its supposed to add the tax rate for a Total Price. The variables inside are representing prices for food and are doubles.
But everytime I press the button the entire program freezes.
Also, i'm trying to wrap the text in 2 textArea boxes, but everytime I try and call the method setLineWrap(true); it shows up on eclipse as not ablee to do that. Heres the two Text areas im trying to put it in:
detailTextArea.setEditable(false);
detailPanel.add(detailTextArea, java.awt.BorderLayout.CENTER);
and
orderTextArea.setEditable(false);
eastPanel.add(orderTextArea);

Use a for each instead.
double orderTotal = 0;
for(Double price : yourOrderPrices) {
orderTotal += price;
}
As for setLineWrap(true), exactly what does Eclipse say?
Solution:
I installed java and Eclipse and tried it out by myself. I created a JTextArea and set the lineWrap to true and it works without complaints. Have you checked that you imported javax.swing.JTextArea and not something else?
My code for reference:
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
JTextArea area = new JTextArea();
area.setLineWrap(true);
}
}

Related

TroubleShooting JOptionPane error

I have a question I have a program where I want to test the users ability to remember a random list of colors. Based off if the users input is right or wrong it will ask for the next color.
So I got it all work up to where the user inputs the first color. Before it has the user input on the first color. The program is already assuming the user input is wrong, even tho it hasn't asked for any input.
I know from previously knowledge I could like flush the buffer, can you do that with JOptionPane?
Or is this another issue I'm not seeing?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class Testing
{
//Intialization of the whole program for everything to pass information
public JFrame main;
public JLabel lbInsturctions;
public JLabel welcomeMessage;
public JLabel homeScreen;
public JLabel homeScreenColors;
public JTextField txtInput;
public int num = 1;
public String colorList = "";
public String[] color = {"red","green","blue","brown","yellow", "gold", "orange", "silver"};
public String[] solution = new String[5];
//sets up the window and random colors
public Testing ()
{
Random r = new Random();
for (int i = 0; i<solution.length; i++)
{
solution[i] = color[r.nextInt(7)];
colorList = Arrays.toString(solution);
}
JOptionPane.showMessageDialog(null, "Lets test your memory. Memorize these colors: " + colorList);
main = new JFrame ();
main.setSize (500,300);
main.setTitle ("Ultimate Colors");
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setLayout(new FlowLayout());
intializeGame();
main.setVisible(true);
}
public void intializeGame ()
{
//All Intiazations
lbInsturctions = new JLabel();
homeScreen = new JLabel();
txtInput= new JTextField(null, 15);
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
main.add(lbInsturctions);
main.add(txtInput);
txtInput.addActionListener(new colorTester());
}
public class colorTester implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//Need to delete or make new window if user pushes ok then
lbInsturctions.setText("Enter color number " + num + ":");
//grabs the users input to see if it is corect
String guess= "";
guess = txtInput.getText();
System.out.println(guess);
//Checks to see if the users input is the same as the initalizaton
if (color[num+1].equalsIgnoreCase(guess) || num > 6)
{
System.out.println("You got it!");
++num;
lbInsturctions.setText("Enter color number " + num + ":");
txtInput.setText("");
}
//if the User input is wrong
else
{
System.out.println("It's a good thing your not graded!");
txtInput.setVisible(false);
lbInsturctions.setText("It's a good thing this is not graded!");
}
if (num == 5)
{
lbInsturctions.setText("You memory is perfect good job!");
txtInput.setVisible(false);
}
}
}
}//end of program
This has nothing to do with flushing buffers.
You're getting user input here: guess = txtInput.getText(); which is in the intializeGame method. Meaning you're getting the text from the txtInput JTextField on its creation, before the user has had a chance to enter anything into the field. I think that you're used to programming linear console programs, where you get the user's input immediately, but that's not how event-driven GUI's work. Instead you must get and react to the user's input on event, here perhaps the ActionListener of some button. Perhaps your code needs a "submit" JButton or something similar, and in its ActionListener, extract the input from the JTextField and respond to it. Do this and your code has a better chance of working.
Other issues:
you don't ever appear to have added your txtInput JTextField into the GUI.
same for the homeScreen JLabel
Edit your new code posted at the bottom of your question has the same problem.

I need to make a reference to a JLabel based off a string

So I have numbered JLabels declared like so (In the class)
OP_1
OP_2
OP_3
etc..
And I have a number and a string.
What I want is that when, for example, the number is 2. I want to change the label text to the content of the string. This is part of a method that is supposed to take a string, put it into the last available JLabel, and then increment the number.
I am very confused, and help would be appreciated.
Here I created an array of JLabels and a method, updateNextLabel(String), which will update the next JLabel with whatever you enter for str.
public class Example {
static int count = 0; //Create a count
static JLabel[] array = new JLabel[3]; //Create an array to hold all three JLabels
public static void main(String[] args) {
//Set the default text for each JLabel
array[0] = new JLabel("This is OP1");
array[1] = new JLabel("This is OP2");
array[2] = new JLabel("This is OP3");
//Here is an example if you wanted to use a for-loop to update the JLabels
for (int x = 0; x < array.length; x++) {
updateNextLabel("This is the new text for OP" + (count + 1));
System.out.println(array[x].getText());
}
}
public static void updateNextLabel(String str) {
array[count].setText(str);
count++;
}
}
Instead of / additional to naming your labels by specific names you can later match them on, I'd think a Map of JLabels with Strings or Integers as keys might be a better approach:
Map<String,JLabel> labelMap = new HashMap<String,JLabel>();
labelMap.put("1", OP_1);
labelMap.put("2", OP_2);
This will allow later access of "The label for key 2" as well as "list me all that labels and find the one with text 2" as well

pass a value obtained from a JButton to a variable

so my problem is that i'm making a really simple number guessing game in java swing, i added a JButton and a JTextField, i want to click the button to get the value written in my text field and then pass it to a do while loop that's gonna make the operation, then i'm going to display it in a JLabel, But i don't know how. I have no JFrame cause i'm gonna send this class to the class that has the JFrame, so i'm adding everything to a JPanel.
hope I was clear, would appreciate some help.
code:
import java.util.Random;
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameDat extends JPanel {
JPanel panel = new JPanel();
FlowLayout layout = new FlowLayout();
Random random = new Random();
JButton enter;
JTextField display;
JLabel result;
int MIN = 1;
int MAX = 50;
int compare = random.nextInt(MAX - MIN + 1) + MIN;
int player;
int guessIt = 0;
public void iniGame(){
enter = new JButton("Pick a number:");
panel.setSize(300,300);
panel.setLayout(layout);
panel.add(enter);
panel.add(display);
panel.add(result);
enter.addActionListener(new CustomActionListenerEnter());
do {
//here should go the value captured from the JTextField instead of a scanner
player = input nextInt();
guessIt++;
if (player > compare)
//this text should go to the jlabel instead of printing it
System.out.println("Number is less than " + player);
else if (player < compare)
//this text should go to the jlabel instead of printing it
System.out.println("Number is greater than " + player);
else
//this text should go to the jlabel instead of printing it
System.out.println(compare + " was my number, it took you " + guessIt + " guesses.");
} while (player != compare);
}
class CustomActionListenerEnter implements ActionListener{
public void actionPerformed(ActionEvent e){
//I wanna pass this value to my do while.
display.getText();
}
}
}
My main recommendation: get rid of the while loop. This loop works with a linear console type program, but this is not how event-driven GUI's work, and that loop will tie up the Swing event thread, rendering your GUI frozen and useless. So, again, get rid of that loop, and instead change the state of a variable in this class based on user's response, and base behavior on that state. So in your ActionListener, get the text from the JTextField, convert it to an int by parsing it, check if it's a decent guess, and notify the user of the results of their guess.
Other issues:
You understand that your class above creates two JPanels, one the JPanel which is the instance of the class itself, and which you add nothing to, and the other one that is referenced by the panel variable that you do add components to. If you're only going to use the panel variable JPanel, then the class should probably not extend JPanel.
What's with the,... //here should go the value captured from the JTextField instead of a scanner and player = input nextInt();? Get rid of this non-compiling code and not helpful code and use the JTextField. It looks like you're trying to shoe-horn console code into a GUI, and this won't work.
Do not use System.out.println(...) or similar code for user interaction, but only for temporary debugging if that. All user interaction should be through the GUI itself, and final production code should not have printlns.
Well it turned out like this at the end, and it works fine. Thanks.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
player = Integer.parseInt(jTextField3.getText());
guessIt++;
if (player > compare)
jTextField1.setText("Number is less than " + player);
else if (player < compare)
jTextField1.setText("Number is greater than " + player);
else
jTextField1.setText(compare + " was my number, it took you " +
guessIt + " guesses.");
}

How do I show an auto vertical scrollbar with JOptionPane and showMessage Dialog?

I have a QuizApplication which will show up the results upon user finished the test.
I have following piece of code which returns quiz result as string:
public String getResult() {
int score = 0;
String[] choices;
String scoreB = "";
for (int i = 0; i < test.length; i++) {
if (test[i].getCorrect() == test[i].getAns()) {
score++;
} else {
choices = test[i].getChoice();
scoreB += "Question " + (i + 1) + " : " + test[i].getQn() + "\n<html></br>choices[test[i].getCorrect() - 1] + "\n\n";
}
} // end of for loop
return result;
}
And then I want to show the result in the form of MessageDialog, so I used:
JOptionPane.showMessageDialog(null, newQuiz.getResult()
But, I want to add a vertical scrollbar onto the JOptionPane.showMessageDialog. How can I do it?
One of the parameters to showMessageDialog is an Object. If this Object is a Component, it will be added to the dialog's view.
I'm not sure why you want to add JScrollBar to the dialog, but you will need to construct a Component containing all the elements you want to display and pass it to the dialog via the message parameter.
Check out How to use Dialogs for details
As a concrete example of #MadProgrammer's suggestion, this example wraps a JTextArea in a JScrollPane and passes the latter to JOptionPane.showMessageDialog(). Also consider this alternative using HTML/CSS.

Java is reading old input files, not new ones

I have some java code which reads text files, adds the contents to a vector and then prints these points to screen using a graph windower.
I have three pointdata.txt files, pointdata1.txt, pointdata2.txt and pointdata3.txt.
The problem i am having is that, even when i change the input file in my driver to pointdata1 or pointdata2, it still runs for pointdata3. I have ensured that there are no occurences of pointdata3 anywhere else in the code. It only appears twice, but i have made sure it is the same.
I have checked the files themselves, they are different. Checked and checked and checked the pathnames, they are different!
Even when i comment out every System.out.println() in the entire code, it still prints everything!
It is asif the code is no longer refereing the the text files, or even running, eclipse just keeps printing what was previously added to the viewport?
Here is the code from my driver:
import java.util.*;
public class PointDriver {
private PointField pointfield;
// testing
public void doAllTests() throws Exception{
this.test1();
this.test2();
}
// Display all points in the file
public void test1() throws Exception{
SimpleIO sIO = new SimpleIO();
System.out.println("Contents of Point File: ");
sIO.displayFile("pointdata1.txt");
//sIO.displayFile("pointdata2.txt");
//sIO.displayFile("pointdata3.txt");
System.out.println();
}
// Load points from a file into a vector and echo them back to the screen
// This uses the StringTokenizer to split the lines into two Strings, then
// uses the Point class to assign the two Strings to x,y double variables
// which form Points. Within the same loop, the points are also displayed
// in a window using the Graph Window class. Maximum x and y values are used
// to determine the dimensions of the GraphWindow, adding 10 units to each
// value to provide a border.
public void test2() throws Exception{
System.out.println("Contents of Point File: ");
System.out.println();
System.out.println("Points are Displayed in a Graph Window");
System.out.println();
Vector lines;
lines = pointfield.getlines("pointdata1.txt");
//lines = pointfield.getlines("pointdata2.txt");
//lines = pointfield.getlines("pointdata3.txt");
Iterator IT;
IT = lines.iterator();
Vector v;
v = new Vector();
double maxX, maxY;
PointField pointfield;
pointfield = new PointField();
GraphWindow gw;
gw = new GraphWindow();
while (IT.hasNext()) {
StringTokenizer st;
String ID = (String)IT.next();
st = new StringTokenizer(ID);
double x = Double.parseDouble(st.nextToken());
double y = Double.parseDouble(st.nextToken());
Point p;
p = new Point(x,y);
v.addElement(p);
int i = v.size();
System.out.println("Point ID: " +i+ " X: "+x+", Y: "+y);
gw.plotPoint(x, y);
}
this.pointfield = new PointField(v);
maxX = this.pointfield.findMaxXPoint();
maxY = this.pointfield.findMaxYPoint();
int width = (int)maxX + 10;
int height = (int)maxY + 10;
gw.setMap(width, height);
}
// Short main method to kick of all tests sequence in doAllTests method
public static void main(String[] args) throws Exception {
PointFieldDriver pfd;
pfd = new PointFieldDriver();
pfd.doAllTests();
}
}
It looks like Eclipse is running an old version of your class file. I'm gathering this as you said that you commented out the printlns, but the output is still displaying.
A few things to check:
In the menu, make sure that Project > Build Automatically is set. If that isn't set, set it, and your problem should be solved.
See whether the timestamp on your class file is changing when you change the source. If it isn't, then Eclipse isn't recompiling it for some reason. You can find the class file probably under the bin folder (if you are using the Eclipse project defaults).
If you find the timestamp is old, try removing the bin folder from outside of Eclipse. Next, right-click on the project and select refresh. Finally, select Project > Clean. This should cause the code to be recompiled into a new class file.

Categories

Resources