Java - How to create a loop for TextFields? [duplicate] - java

This question already has answers here:
adding elements defined in FXML to list with loop
(3 answers)
Closed 3 years ago.
Basically, I would like to make a loop which would change the name of every TextField to a name stored in a folder. I fully understand how to make loops for int values, but completely don't know how to make it to affect a methods (like I show it below). Any ideas how to solve the problem?
Check the code and I am sure you will understand what I mean
#FXML
private TextField t1;
#FXML
private TextField t2;
// etc...
#FXML
void music(ActionEvent event) {
if (event.getSource() == dmusic) {
File folder = new File("C:\\eclipse\\MP2");
File[] list = folder.listFiles();
for (int i = 0; i < list.length; i++) {
System.out.println(list[i].getName());
// Here i would like to update TextField name for every "t" method like I did below, but without writing it all the time.
}
// t1.setText(list[0].getName()); // can't make infinite "t"'s and would like to make it in a loop
// t2.setText(list[1].getName());
// t3.setText(list[2].getName());
// t4.setText(list[3].getName());
// t5.setText(list[4].getName());
// t6.setText(list[5].getName());
// ...
}
}

Try using an arraylist
Arraylist<TextField> fields = new ArrayList<>();
<add TextFields to arraylist>
and then use
for(TextField field : fields) {
field.setText("");
}
or
for(int i=0; i< fields.size(); i++){
fields.get(i).setText("");
}
to access your individual text fields.

Related

Removing an array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Removing an element from an Array (Java) [duplicate]
(15 answers)
Closed 4 years ago.
Got a simple auction program running, only problem is that if a user is removed before auction is closed his/hers bids are supposed to be removed. I dont have it 100% down yet but I think I am on the right path.
The bids have to be arrays and right now it is kinda removed or just moved maybe. This was a the error earlier.
Top Bid:[Wow 400 kr, Boy 311 kr, Man 33 kr, Dude 2 kr]
command>remove user
Name>wow
Wow has been removed from registry
command>list auctions
Auction # 1: Item. Top Bid:[Boy 311 kr, Man 33 kr, Exception in thread "main" java.lang.NullPointerException
public void removeBid(String name) {
for(int a = 0;a < bidIndex; a++) {
if(bids[a].getUser().getName().equals(name)) {
bids[a]=null;
bidIndex--;
break;
}
}
sortBids();
public void sortBids() {
if(bidIndex > 1) {
for(int a = 0; a < bidIndex -1; a++) {
for(int b = a + 1; b < bidIndex; b++) {
if(bids[a] == null || bids[a].getBid() < bids[b].getBid()) {
Bid temp = bids[a];
bids[a] = bids[b];
bids[b] = temp;
}
}
Arrays cannot change size once initialized. If you create an array new String[10]; it will forever have 10 items (which are null by default). Setting an index to null doesn't change this.
String[] items = new String[] {"String1", "String2", "String3"};
items[1] = null;
This arrays would now look like [String1, null, String3].
If you need to change arrays as much as it seems, you're better off using a List or Map.
I would suggest using a HashMap if you want to easily link one object to another. In this case it looks like you'd be linking a String (name) to the Bid object.
Map<String, Bid> bids = new HashMap<String, Bid>();
Bid bid1 = new Bid(/*...*/);
Bid bid2 = new Bid(/*...*/);
// Add bids to the map
bids.put("Wow", bid1);
bids.put("Boy", bid2);
// Get any of these objects
Bid retrievedBid = bids.get("Wow");
// Or remove them
bids.remove("Wow");
HashMaps are similar in concept to associative arrays from other languages, where you have a key -> value relationship. Each key is unique, but the value can repeat.
They can also be converted to arrays if the final result you need is an array.
Bid[] bidsArray = new Bid[0];
bidsArray = bids.values().toArray(bidsArray);
One way you can achieve this is to convert the array to a list and then remove the bid using Java streams and convert back.
List<Bid> bidsList = Arrays.asList(bids);
bidsList = bidsList.stream()
.filter(n -> !n.getUser().getName().equals(name))
.collect(Collectors.toList());
bids = bidsList.toArray(new Bid[bidsList.size()]);

Using a Loop to add ActiveListeners in one class for a button in multiple instances of another class

I have a class called InstructionBlock, which is a JPanel
On my main form, which is a JFrame, I've created 6 instances of InstructionBlock. I need to have my main form do something based on a button being pressed in the instances of InstructionBlock and it needs to know which instances had the button pressed.
I have the following code in the class InstructionBlock:
public void InstBlockAddActionListener(ActionListener al) {
CheckMarkClicked.addActionListener(al);
}
I've add the instances of InstructionBlock to my main form as follows:
ArrayList<InstructionBlock> instructionPane = new ArrayList<>();
int i;
for (int i = 0; i<6;i++) {
instructionPane.add(new InstructionBlock());
InstructionLayer.add(instructionPane.get(i));
}
Now here is where I have an issue:
for (i = 0; i<6;i++) {
instructionPane.get(i).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(i+1);});
}
When I hit the 1st button, I expected to pass a value of 1, but I'm passing a value of 7
I know I can do it as follows:
instructionPane.get(0).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(1);});
instructionPane.get(1).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(2);});
instructionPane.get(2).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(3);});
instructionPane.get(3).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(4);});
instructionPane.get(4).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(5);});
instructionPane.get(5).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(6);});
But I don't know why the loop isn't working. Is there another way to make it work?
Your problem is here:
for (i = 0; i<6;i++) {
instructionPane.get(i).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(i+1);});
}
You must be making i a field of the class for this to compile, and by doing this, you set it to 7 and only 7 after this for loop has finished. To solve this, don't use a class field but rather an inner final variable, something like:
for (int j = 0; j < 6; j++) {
final int finalIndex = j + 1;
instructionPane.get(j).InstBlockAddActionListener((ActionEvent ae) -> {
InstructionCheckMarkButtonPressed(finalIndex);
});
}
As a side recommendation, and in order to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

how to add text rather than replacing it in textfields java

I have multiple buttons containing some information.
Now I want that the information written on the buttons are appended when i press them i.e when i press the first button
- the information gets printed into text field
When I press second button
- the information written on button gets appended or added into the text field with the older information (data in button 1).
code for what I am trying is:
private void EActionPerformed(java.awt.event.ActionEventevt) {
String x = ans.getText();
for(int i = 0; i < x.length(); i++) {
ans.setText("H");
}
}
private void FActionPerformed(java.awt.event.ActionEvent evt) {
String x = ans.getText();
for(int i = 0; i > x.length(); i++) {
ans.setText("A");
System.out.println("completed");
}
}
Simply:
ans.setText(ans.getText() + newString);
There are a few ways to this, setText is one, but it's not particularly efficient (it's easier to type though), as you are creating additional temporary objects though the process
If you need to update the field often, you might consider using something more like...
Document doc = userNameField.getDocument();
doc.insertString(doc.getLength(), newString, null);

Java - Iterate through an array everytime a button is pressed

I would like to iterate through a list every time a button is pressed, using JButton, JTextField and event's ActionListener. So every time the "next" button is pressed the next item in the array should be displayed in a JTextField. I have already created the getters, setters and constructor, it's literally only the following piece I'm having trouble with.
#Override
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String[] item = getThing();
for(int i = 0; i < 3; i ++){
String currentI = item[i];
}
if(source.equals(btnNxt)){
txtDisplayField.setText(currentI);
}
}
In the if statement I receive an error "Cannot find symbol", referring to currentI.
The currentI variable went out of scope at the end of the loop. You should declare it outside of the for loop.
By the way, the code still won't work properly, because you set the value to the last item of the array every time. You should step only once, and if you are at the last item, jump to the first one.
You're initializing your currentI String within your for loop's scope.
The variable is therefore inaccessible outside your for loop.
Move your equality check and assignment inside the loop.
for(int i = 0; i < 3; i ++){
String currentI = item[i];
if(source.equals(btnNxt)){
txtDisplayField.setText(currentI);
// stop iteration as you already found a match
break;
}
}
I don't see why you need a for loop at all.
Simply :
int ctr = 0;
public void actionPerformed(ActionEvent evt){
ctr++;
if(ctr<item.length)
txtDisplayField.setText(iter[ctr]);
}
That should solve your problem

Nullpointer exception java runtime [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
The program looks slightly advanced; it is not. Simple manipulation of array.
The program compiles correctly, however, it encounters an exception run-time.
Exception in thread "main" java.lang.NullPointerException
at Ordliste.leggTilOrd(Tekstanalyse.java:85)
at Tekstanalyse.main(Tekstanalyse.java:23)
So there is something wrong with if(s.equalsIgnoreCase(ordArray[k])).
I cannot see why. It even provides the correct output.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Tekstanalyse {
public static void main(String[] args) throws FileNotFoundException {
Ordliste ol = new Ordliste();
ol.lesBok("scarlet.text");
ol.leggTilOrd("A");
}
}
class Ordliste {
private int i = 0;
private String[] ordArray = new String[100000];
private int antForekomster;
private int arrStorrelse = 0;
public void lesBok(String filnavn) throws FileNotFoundException {
File minFil = new File(filnavn);
Scanner scan = new Scanner(minFil);
while (scan.hasNextLine()) {
ordArray[i] = scan.nextLine();
//System.out.println(ordArray[i]);
i++;
arrStorrelse++;
}
System.out.println("Array size: " + arrStorrelse + " Capacity: " + ordArray.length);
}
public void leggTilOrd(String s) {
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse];
}
}
}
}
I'm pretty sure the error is right here:
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
} else {
s = ordArray[arrStorrelse]; // <- dangerous
}
}
As I said in the comment, ordArray could contain null elements if the read text file does not contain 100.000 lines of text. If this is the case, the above line would write null to s because s.equalsIgnoreCase(null) is false.
You should think about using a list instead of an array.
private List<String> ordList = new ArrayList<String>();
(or use a different variable name, it is up to you)
Then you can add new entries to the list using ordList.add(scan.nextLine());. This list won't contain any null elements and your mentioned problem should be gone.
I would highly recommend you to simply use a debugger to debug your code , but here goes:
in your lesBok method you fill your array with strings and make a counter arrStorrelse. to be the amount of elements in the array you made. however the array is filled for indexes 0 to n-1. and arrStorrelse is equal to N you did however allocate space in the array for this. so when in leggTilOrd() you iterate the first time and you enter the else clause you do this
for (int k = 0; k < ordArray.length; k++) {
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
}
else {
int arrStorrelse2=arrStorrelse;
s = ordArray[arrStorrelse];
}
in that else clause s is set to ordArray[arrStorrElse]; however arrStorrElse is at that moment one higher than the last intialised element of your array. so it sets s to the null pointer.
then the next iteration of your loop in the if clause
if (s.equalsIgnoreCase(ordArray[k])) {
antForekomster++;
System.out.println("Den har vi sett for!");
the s.equalsIgnoreCase() call is done on an s that is null that's where the null pointer exception comes from.
you need to change the arrStorrElse assignment you haven't explained what it should do so i can't do that for you also try to learn how to debug your code here is a usefull link:
http://www.tutorialspoint.com/eclipse/eclipse_debugging_program.htm
I have compiled and tested your code.
s.equalsIgnoreCase(null)
throws nullPointerException.
Maybe you should try to use ArrayList instead of Array to avoid iterating through nulls.
It took me some time to figure out why the NullPointerException occurs and I have to agree with Piotr and Tom: The NPE is caused by the line
s.equalsIgnoreCase(ordArray[k])
and a side-effect in your code. This side-effect is introduced by reassigning the parameter s in the else-branch to null (this value comes from ordArray[arrStorrelse]). After this reassignment happened, you will have something like this:
null.equalsIgnoreCase(ordArray[k])
And voila, there is the NullPointerException.

Categories

Resources