Choose what an array stores based on button press - java

I'm trying to find a way to pick what an array stores based on which button the user presses on a GUI.
Obviously this will not compile due to the variable name being the same.
The calculations are performed outside of the loop but use "values". I just want the user to be able to determine what values are set in the array based on what button they press. The obvious issue is not being able to use the name "values" twice, which is where I am having a problem as I have a for loop that requires the variable "values" and I don't want to have to be re adding the code several times for each data set when there is most likely an easy workaround that I am currently not seeing.

Just pull the declaration out:
double[] Xvalues = null;
if (e.getSource() == X1btn) {
Xvalues = new double[]{2001,350,799,1004};
}
else if (e.getSource() == X2btn) {
Xvalues = new double[]{5,62,28,500};
}

A better approach would be to subclass JButton and associate a set of values with each instance. To retrieve the button's values, include an accessor.
Example
public final class JArrayButton extends JButton{
private final double[] values;
public JArrayButton(double[] values){
this.values = values;
}
// ... other stuff (e.g. constructors)
public final double[] getValues(){
return values;
}
}

What if you create the array ourside the loop.
double Xvalues[] = new Xvalues[5]; //or whatever size you want
and then use if/else statement
if (e.getSource() == X1btn) {
Xvalues ={2001,350,799,1004};
} else if (e.getSource() == X2btn) {
Xvalues={5,62,28,500};
}

Related

Java arrays - How to go through List and set specific value

First i add new Popotnik in List popotnik depending on how big it is, which is working fine - function prostaMesta. Then i want to go through list popotnik and set popotnik value depending on where it is in for, but value of i will always be 0 everytime it is being called. Also i have break there as i only want to set one popotnik at the time. How should i increment (i) while having some sort of break in there?
Also if(popotnik.get(i) == null){} is not being called, but values inside popotnik are null(s)
private List<Popotnik> popotnik = new ArrayList<Popotnik>();
public void prostaMesta(List<Popotnik> popotnik, int sedez){
stanovanje.setPostle(sedez);
for(int i=0; i<stanovanje.getPostle(); i++){
popotnik.add(new Popotnik());
}
System.out.println(popotnik);
}
public void dodajPotnika(List<Popotnik> popotnik, Popotnik popotnik2){
for(int i=0; i<popotnik.size(); i++){
if(popotnik.get(i) == null){
setPopotnik(popotnik, i);
popotnik.set(i, popotnik2);
break;
}
}
System.out.println(getPopotnik());
}
public void setPopotnik(List<Popotnik> popotnik, int i){
this.popotnik = popotnik;
}
public List<Popotnik> getPopotnik(){
return popotnik;
}
Main class:
List<Popotnik> alPopotnik = new ArrayList<Popotnik>();
if(x.equals("p")){ //inside of a loop when prostaMesta() is being called
potovanje.prostaMesta(alPopotnik, sedez);
}
`if(x.equals("d")){` //inside of a loop when dodajPotnika() is being called
System.out.println("Vnesi ime: ");
String ime = skener.next();
Popotnik popotnik = new Popotnik(ime);
potovanje.dodajPotnika(alPopotnik, popotnik);
}
The if(popotnik.get(i) == null) is never true because objects on the list are not null. You initialize them in the for loop in prostaMesta.
If you have some fields inside the Popotnik class then they are null, but object itself is not.
You would need to do something like popotnik.get(i).getName() == null.
Besides, if you only want to add a number at the end of popotnik's name then it isn't necessary to initialize a list with empty objects.
You could just add objects to list using a different constructor.
For example popotnik.add(new Popotnik("Popotnik"+(popotnik.size()+1))).
It's not pretty but I think initialization like this here is not necessary.

Java array objects "null"

I have problem with my integer arrays, for example one. I have class with objects, and i have different class, where these objects are incremented after button click, but I got "null" values and NullPointerExpection. I had this all working, when i hade just, for example "int Money;", but my codes was 12000 lines, and i tried to make it easier to read, etc. But now with array they don't work. I got working this thing with For Loops , but how I understand, i can't make it with loops, because i want to later load these values from savefile.
CarMainClass (This one doesn't work) :
package Clicker;
public class MainHolder {
public Integer main[] = new Integer[8];
public MainHolder(){
}
public void MainMaker(int k){
}
public void MakeMain(){
MainMaker(0); // Money
MainMaker(0); // Money Clicks
MainMaker(0); // Boxes
MainMaker(0); // Boxes Clicks
MainMaker(1); // Boxes Level
MainMaker(1); // Player Level
MainMaker(1); // Garage Level
MainMaker(0); // Garage Slots
}
}
CarMainClass (That works, with for loop) :
package Clicker;
public class MainHolder {
public Integer main[];
public MainHolder(){
main = new Integer[8];
for(int i=0; i <8;i ++){
if(i ==4 || i ==5 || i ==6){
MainMaker(1,i);
}else{
MainMaker(0,i);
}
}
}
public void MainMaker(int k,int p){
main[p] = k;
}
public void MakeMain(){
}
}
And button :
//Money Button Click
if(ae.getSource() == jbtnMoney) {
CarMain.main[0] += 1;
MoneyLabel.setText("Money: " + CarMain.main[0]);
CarMain.main[1] += 1;
MoneyClicksLabel.setText("Money Clicks: " + CarMain.main[1]);
}
Application GUI when working : WorkingImage
Application GUI when dosn't work + error : NoWorkingImage
Is it a full code of CarMainClass? It seems that the method MainMaker doesn't contain any executable code so it doesn't do anything when you call it. The button click is ok.
The initialised array is empty - contains only null values and that is why it returns null - when you reference the value on the GUI.
You need to change it to this (I assume that each number describes object):
package Clicker;
public class MainHolder {
public Integer main[] = new Integer[8];
public MainHolder(){
MakeMain();
}
public void MainMaker(int k,int p){
main[p] = k;
}
public void MakeMain(){
MainMaker(0,0); // Money
MainMaker(0,1); // Money Clicks
MainMaker(0,2); // Boxes
MainMaker(0,3); // Boxes Clicks
MainMaker(1,4); // Boxes Level
MainMaker(1,5); // Player Level
MainMaker(1,6); // Garage Level
MainMaker(0,7); // Garage Slots
}
}
But your solution to use loops make actually more sense. Why you can't store it into a file? You should define the the integers which you use to describe the application as constants - final Integer money = 0 and so on.
You can store the values into a file and use the index to map the values to the corresponding values. Or store it as map.

Action Event with Toggle Buttons in Java - (Program not working)

This program is supposed to save the button value "ab" to the ArrayList whenever the button is pressed, but the if command seems to never work, I tried removing it and seeing if it works, it does and the ArrayList is updated with the new value. So if I pressed the button or not when it appears in the J Windows, nothing happens.
This program later on saves the array to a file, so basically nothing is saved if the if is there and I clicked as many times I wanted, but if the if loop in this one goes then it works
public void actionPerformed(ActionEvent a)
{
ArrayList<String> aList = new ArrayList<String>();
if (a.getActionCommand() == "ab")
aList.add("ab");
}
So if this was done it world print out and aList would be filled with ab in the zero index :
public void actionPerformed(ActionEvent a)
{
ArrayList<String> aList = new ArrayList<String>();
aList.add("ab");
}
Firstly, aList is local variable and it'll be removed on the exit of the method.
Secondly:
a.getActionCommand() == "ab"
You must compare String objects using equals method:
a.getActionCommand().equals("ab")
or
"ab".equals(a.getActionCommand()) //hack for prevention null reference after a.getActionCommand()
There is reference comparison in your example, but using equals you'll be compare objects, not references.
Your list only exists in the scope of the method. In order to work with it from the "outside" you should use it as a instance variable.
For example:
public class A implements ActionListener {
private final List<String> aList;
public A() {
aList = new ArrayList<String>();
}
...
public void actionPerformed(ActionEvent a)
{
if (a.getActionCommand().equals("ab")) {
aList.add("ab");
}
}
}

Is this proper use of storing values into an array via getText()?

In my Java program's constructor I have the following:
thirdRow.add(button);
button.setActionCommand("Sumbit");
button.addActionListener(this);
And here is the corresponding actionPerformed method that's supposed to take 3 values from some textfields and store them into arrays:
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
if (arg == "Submit")
{
//enlarge arrays
qtyStr = enlargeArray(qtyStr);
typeStr = enlargeArray(typeStr);
colorStr = enlargeArray(colorStr);
//add from textfields into current
qtyStr[qtyStr.length-1] = qty.getText();
typeStr[typeStr.length-1] = type.getText();
colorStr[colorStr.length-1] = color.getText();
}
}
//method to enlarge an array by 1
public String[] enlargeArray(String[] currentArray)
{
String[] newArray = new String[currentArray.length + 1];
for (int i = 0; i<currentArray.length; i++)
newArray[i] = currentArray[i];
return newArray;
}
When I run the application, populate the textfields, and click the submit button nothing happens. How can I verify that my string arrays are being appended like they're supposed to?
You've a problem here: if (arg == "Submit")
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Also, for safety's sake, I try to use String constants wherever possible so as not to be tripped up by misspellings.
If you want to do your code this way, I would probably do two things:
1) maintain index fields for each array for the next free index, and
2) I wouldn't recommend resizing your array by 1 each time, as our current code is running through the array 2 n times (n = array length), 1st to initialize the array, and 2nd to create a new array.
Two options to optimize thisL one would be be to look into the Arrays class. it contains methods such as Array.copyOf() that can perhaps be useful here. You could also check if the array is full, and if it is then resize it by a number greater than one to reduce extra work.
For instance:
import java.util.Arrays;
class Test{
private String[] a;
private int next;
public Test(int size){
a = new String[size];
next = 0;
}
public void add(String s){
if(next == a.length){
Arrays.copyOf(a, a.length+1);
}
a[next] = s;
next++;
}
}
The easiest way would be to use an ArrayList (or any class that implements the java.util.List interface), as previously mentioned by Jon Skeet - it will do all the work for you.

Printing the wrong thing

for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel<Integer> modelAge = new DefaultComboBoxModel<Integer>();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox<Integer> ageEntries = new JComboBox<Integer>();
ageEntries.setModel(modelAge);
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Selected:" + ItemEvent.SELECTED);
}
}
}
Problem: When I choose an age, it prints out 1, regardless of the age I've choosed. For example, if I choose the number 7, it prints out 1. If I choose 56, it prints out 1. Any ideas? I'm stumped.
Use this to retrieve the selected item ..
((JComboBox)event.getSource()).getSelectedItem();
EDIT: should be ((JComboBox<Integer>)event.getSource()).getSelectedItem(); as you are using generics. And "Yes" this will come inside your event method.
EDIT 2: you are getting the warning because we cannot determine whether JComboBox should have a Generic parameter. Compiler raises this warning because it thinks its unsafe to do such casting.
#SuppressWarnings("unchecked")
((JComboBox<Integer>)event.getSource()).getSelectedItem();
System.out.println("Selected:" + ItemEvent.SELECTED);
That is not the selected element you are printing here, but just some internal event type code (to mark this as a selection event). It is a constant value defined by the ItemEvent class.
Try event.getItem(). That should return the selected item.
ItemEvent.SELECTED is a constant representing the flag that says 'an item was selected'. You need to use the other methods of the ItemEvent object to extract your original combo box and find the selected item...
check here: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/ItemEvent.html#SELECTED
ItemEvent.SELECTED is a constant, below is the source of ItemEvent.java.
package java.awt.event;
public class ItemEvent extends AWTEvent {
......
/**
* This state-change value indicates that an item was selected.
*/
public static final int SELECTED = 1;
......
}

Categories

Resources