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

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");
}
}
}

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.

Getting input directly in ArrayList

I am new to JAVA. This is what I have to do:
User inputs as many marks as he wants by writing a number and pressing add button doing that over and over and all those marks are added in arraylist. After he is done, he presses the sort button and all the marks are sorted and displayed.
This is what I have:
ArrayList <Integer> marks=new ArrayList();
private void addActionPerformed(java.awt.event.ActionEvent evt) {
marks.add(Integer.parseInt(marksinput.getText()));
Collections.addAll(marks);
}
private void sortActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList <Integer> marks=new ArrayList();
marks.add(Integer.parseInt(marksinput.getText()));
Collections.addAll(marks);
Collections.sort(marks);
marksoutput.setText(marks + "\n");
}
The problem I am having is it does not display all the numbers I added before. It just displays the last number. Any help is appreciated and thank you in advance!
You need to push up the marks list at class level. Remember, variables created inside a method only have method scope.
//Move it outside of method at class level
ArrayList <Integer> marks=new ArrayList();
private void addActionPerformed(java.awt.event.ActionEvent evt) {
{
//Push the latest value into marks list, it will already contain all previous entries as we are not re initializing it.
marks.add(Integer.parseInt(marksinput.getText()));
}
private void sortActionPerformed(java.awt.event.ActionEvent evt) {
Collections.sort(marks);
marksoutput.setText(marks + "\n");
}
I am not sure where the events are actually saved; you are adding them to the marks array but that is local to the addActionPerformed method and lost once that is completed.
It is hard to say with just the code you posted but maybe you can try to make marks a global object in your class.

Calling an arrayList from another class which is private

I am trying to display an arraylist in a gui. However I am getting some troubles. I need to check if my game is legal, if it is not legal then it calls getProblems which displays the arraylist. I tried to call getProblems directly in the GUI class however it will show the array as empty. (Since it's not checking if it's legal). I also tried to call isLegal then getProblems but you cannot do this in a JOptionPane. Any tips on how I can call it accross?
GetProblems class
protected List < String > getProblems() {
return displayOutput;
}
IsLegal Class
public boolean isLegal() {
boolean legality;
if (checkRowConstraints().isEmpty()) {
legality = true;
} else {
getProblems();
legality = false;
}
return legalCheck;
}
GUI:
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
puzzle.getProblems(),
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
Here is difference between Actual display of GUI result and result i'm trying to get.
Further Problem found:
I need to return the arraylist then empty it. Fixed
Presently, there is an implicit call to the List's toString() method when you call puzzle.getProblems() within the JOptionPane. So rather than get the contents of the List, which is what you want, you're getting whatever toString() is giving you.
You're not going to get the contents of the List unless you iterate over it first.
You could try something like this. (Note, this is untested code. For demo purposes.)
String formattedString = "";
//let's iterate over our List and build a formatted string for output
for(String element : puzzle.getProblems())
{
formattedString += element;
}
Then you can output this formatted String
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
formattedString,
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);

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.

Choose what an array stores based on button press

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};
}

Categories

Resources