View difference between Paste ID: eYGfThcT and QrHthddv
SHOW: | | - or go back to the newest paste.
1
I have a Jframe that includes a Jspinner. When the JSpinner is increased a new JTextField is created in my panel headerPanel. The script creates the textboxes with an integer attached to their variable name (tFrame0, tFrame1, and so on).
2
 
3
        spinner = new JSpinner();
4
        spinner.addContainerListener(new ContainerAdapter() {
5
            @Override
6
            public void componentAdded(ContainerEvent arg0) {
7
                boxesChanged();
8
            }
9
        });
10
        spinner.addChangeListener(new ChangeListener() {
11
            public void stateChanged(ChangeEvent arg0) {
12
                int spinnerValue = (Integer) spinner.getValue();
13
                if (spinnerValue == headerPanel.getComponentCount()) {
14
                    System.out.println("Error, spinner shouldn't change to same value");
15
                }
16
 
17
                if (spinnerValue < headerPanel.getComponentCount()) {
18
                    headerPanel.removeAll();
19
                }
20
 
21
                while (spinnerValue > headerPanel.getComponentCount()) {
22
                    boxesChanged();
23
 
24
                    // frame.getContentPane().add(tField);
25
                    frame.revalidate(); // For JDK 1.7 or above.
26
                    // frame.getContentPane().revalidate(); // For JDK 1.6 or below.
27
                    frame.repaint();
28
                }
29
            }
30
        });
31
 
32
Now I'm trying to loop through my code based on the number of components in my headerPanel but I don't know how to append my for loop int i to a variable name.
33
 
34
Variables
35
 
36
    Public JTextField() tField;
37
    Public String nameTField = "tFrame";
38
    Public Object[] inputData;
39
   
40
 
41
Creating the text boxes
42
 
43
    public void boxesChanged() {
44
        tField = new JTextField();
45
        tField.setName(nameTField + (headerPanel.getComponentCount()));
46
        headerPanel.add(tField);
47
    }
48
 
49
Loop attempt (Located in a separate class with access to the GUI)
50
 
51
    int hp = headerPanel.getComponentCount();
52
    inputData = new Object[hp];
53
    for (int i = 0; i < hp; i++) {
54
        tField = new JTextField();
55
        tField.setName(nameTField + i);
56
        inputData[i] = tField.getText();
57
    }
58
59
EDIT
60
 
61
I was able to make some headway with this https://stackoverflow.com/questions/24642059/for-loop-output-in-jframe?fbclid=IwAR1piMmk8EjygobXdxkyxfM9idA5pCh4WJrpBx9QINbsMcmc5MvaUZ3gb0I. When creating the textboxes, I can assign a Document Listener to them and then they are able to pass me information. I'm still having some issues with how I can assign each input from these to my for loop however.
62
 
63
    public void boxesChanged() {
64
    tField = new JTextField();
65
    tField.setName(nameTField + (headerPanel.getComponentCount()));
66
    tField.getDocument().addDocumentListener(new DocumentListener(){
67
          public void changedUpdate(DocumentEvent e) {
68
            warn();
69
          }
70
          public void removeUpdate(DocumentEvent e) {
71
            warn();
72
          }
73
          public void insertUpdate(DocumentEvent e) {
74
            warn();
75
          }
76
 
77
          public void warn() {
78
             if(tField.getText()!=null) {
79
                 System.out.println(tField.getText());
80
             }
81
          }
82
    });
83
 
84
    headerPanel.add(tField);
85
 
86
    }
87
 
88
EDIT 2
89
 
90
I've managed to make a change that adds each textfields information to my inputData Object[], but only if I add data sequentially (tField0 must be filled out, then tField1, etc).
91
 
92
For some reason each time I add a new JTextField it changes the document listener to that field only, even though I create the document listener in each new JTextField.
93
 
94
        public void boxesChanged() {
95
        int hp = headerPanel.getComponentCount();
96
 
97
        tField = new JTextField();
98
        textFieldList.add(tField);
99
        tField.setName(nameTField + hp);
100
 
101
        tField.getDocument().addDocumentListener(new DocumentListener() {
102
 
103
            public void changedUpdate(DocumentEvent e) {
104
                warn();
105
            }
106
 
107
            public void removeUpdate(DocumentEvent e) {
108
                warn();
109
            }
110
 
111
            public void insertUpdate(DocumentEvent e) {
112
                warn();
113
            }
114
 
115
            public void warn() {
116
                int digits = 1;
117
 
118
                if (hp > 9) {
119
                    digits = 2;
120
                }
121
 
122
                String getFieldString;
123
                int getFieldNum;
124
 
125
                getFieldString = tField.getName().substring(tField.getName().length() - digits);
126
 
127
                getFieldNum = Integer.parseInt(getFieldString);
128
 
129
                if (tField.getText() != null) {
130
                    Object[] currentData = new Object[getFieldNum + 1];
131
                    currentData[getFieldNum] = tField.getText();
132
 
133
                    inputData[getFieldNum] = tField.getText();
134
 
135
                    for (int i = 0; i < inputData.length; i++) {
136
                        if (inputData[i] != null) {
137
                            System.out.println("for i = " + i + ": " + inputData[i]);
138
                        }
139
 
140
                    }
141
                }
142
            }
143
        });
144
 
145
 
146
With this setup if I set the default JTextField to "Box 1" my console output will look like this.
147
 
148
    for i = 0: B
149
    for i = 0: Bo
150
    for i = 0: Box
151
    for i = 0: Box
152
    for i = 0: Box 1
153
 
154
If I create the second JTextField and then type in "Box 2" in that field it will output like this
155
 
156
    //Same as above
157
    for i = 0: Box 1
158
    for i = 1: B
159
    for i = 0: Box 1
160
    for i = 1: Bo
161
    for i = 0: Box 1
162
    for i = 1: Box
163
    for i = 0: Box 1
164
    for i = 1: Box
165
    for i = 0: Box 1
166
    for i = 1: Box 2
167
 
168
However say I decide to change the boxes to "Box 0" and "Box 1" my console after making both of these changes will output this.
169
 
170
    //Same as above
171
    for i = 0: Box 1 //Deleted "1" from box 1
172
    for i = 1: Box 2 //Deleted "1" from box 1
173
    for i = 0: Box 1 //Added "0" to former box 1
174
    for i = 1: Box 2 //Added "0" to former box 1
175
    for i = 0: Box 1 //Deleted 2 from box 2
176
    for i = 1: Box //Deleted 2 from box 2
177
    for i = 0: Box 1 //Added 1 to former box 2
178
    for i = 1: Box 1 //Added 1 to former box 2
179
 
180
If I were to keep going and add a 3rd JTextField etc. only the last created JTextField will show a change in output on the console.
181
182
EDIT 3
183
184
I have managed to pass the code along a little further now. Now I can store all of my data properly within an ArrayList that will hold my data, but only if I enter my data sequentially.
185
186
Variables
187
 
188
    Public JTextField() tField; //textField element is public and created in boxesChanged()
189
    Public String nameTField = "tFrame"; //Name of TextField before appending variable in spinner
190
    Public Object[] headerData; //inputData changed to headerData in Edit 3.
191
    private ArrayList<JTextField> textFieldList = new ArrayList<JTextField>(); //ArrayList that holds JTextFields
192
    private JPanel headerPanel; //Panel that holds JTextFields
193
194
195
My Spinner
196
197
    spinner = new JSpinner(); //New spinner
198
		spinner.addContainerListener(new ContainerAdapter() {
199
			@Override
200
			public void componentAdded(ContainerEvent arg0) { //On creation Spinner value is 1, so runs boxesChanged() to set the first JTextFrame
201
				boxesChanged();
202
			}
203
		});
204
		spinner.addChangeListener(new ChangeListener() {
205
			public void stateChanged(ChangeEvent arg0) { //Each time the spinner changes
206
				int spinnerValue = (Integer) spinner.getValue();
207
				if (spinnerValue == headerPanel.getComponentCount()) {
208
					System.out.println("Error, spinner shouldn't change to same value"); //Was reaching this during some debuging earlier, but not recently
209
				}
210
211
				if (spinnerValue < headerPanel.getComponentCount()) {
212
					headerPanel.removeAll(); //removes all existing JTextFields
213
				}
214
215
				while (spinnerValue > headerPanel.getComponentCount()) { //Populates headerPanel with JTextFields until spinnerValue == headerPanel.getComponentCount
216
					boxesChanged();
217
218
					frame.revalidate();
219
					frame.repaint();
220
				}
221
			}
222
		});
223
224
My boxesChanged() method
225
226
    	public void boxesChanged() { //Runs whenever spinner value != number of JTextPanels in headerPanel
227
		int hp = headerPanel.getComponentCount();
228
229
		tField = new JTextField(); //Create JTextField
230
		textFieldList.add(tField); //adds the current JTextField to ArrayList<JTextField> textFieldList
231
		tField.setName(nameTField + hp); //sets name of current JTextField to String nameTField + current JTextPanelCount (tFrame0, tFrame1, ...)
232
233
		tField.getDocument().addDocumentListener(new DocumentListener() { //Adds a listener to each instance of JTextField
234
235
            //If any changes to JTextField, runs warn()
236
			public void changedUpdate(DocumentEvent e) {
237
				warn();
238
			}
239
240
			public void removeUpdate(DocumentEvent e) {
241
				warn();
242
			}
243
244
			public void insertUpdate(DocumentEvent e) {
245
				warn();
246
			}
247
248
			public void warn() {
249
250
				int digits = 1; //sets the number of digits to subtract from substring
251
252
				if (hp > 9) { //if >9 uses 2 didgits, Spinner max is 100, starting at 0, so 99 is max
253
					digits = 2;
254
				}
255
256
				String getFieldString; //String used to hold substring
257
				int getFieldNum; //int for parseInt of getFieldString
258
259
				getFieldString = tField.getName().substring(tField.getName().length() - digits); //Gets the last digit(s) from tField.getName
260
261
				getFieldNum = Integer.parseInt(getFieldString); //Parses substring into int
262
263
				headerData = new Object[hp + 1]; //Create headerData with size of number of JTextField +1 (if 0, will instantiate a null array)
264
265
				if (tField.getText() != null) { //null check
266
267
					headerData[getFieldNum] = tField.getText(); //sets the headerData value to current JTextField's text
268
269
					for (int i = 0; i < textFieldList.size(); i++) { //Loop through to see if each text field list contains correct data
270
						System.out.println("TFL i :" + i + " " + textFieldList.get(i).getText());
271
					}
272
				}
273
			}
274
		});
275
276
		headerPanel.add(tField); //Accidentally left this part out of the previous edit, hope it wasn't what was causing my issue
277
278
	}
279
280
With this setup if I set the default JTextField to "Box 1" my console output will look like this.
281
282
    TFL i :0 B
283
    TFL i :0 Bo
284
    TFL i :0 Box
285
    TFL i :0 Box 
286
    TFL i :0 Box 1
287
    TFL i :0 Box 1
288
    TFL i :1 B
289
    TFL i :0 Box 1
290
    TFL i :1 Bo
291
    TFL i :0 Box 1
292
    TFL i :1 Box
293
    TFL i :0 Box 1
294
    TFL i :1 Box 
295
    TFL i :0 Box 1
296
    TFL i :1 Box 2
297
298
However, this is only if I add data sequentially (tField0 must be filled out before I increase the spinner, then tField1 must be filled out, increase the spinner, etc.).
299
Otherwise I get an ArrayIndexOutOfBoundsException at
300
301-
    headerData[getFieldNum] = tField.getText();
301+
    headerData[getFieldNum] = tField.getText();
302
303
304
Edit 5
305
306
Variables
307
308
    private static String nameTField = "tField";
309
310
    private Object[] headerData;
311
312
    public String name;
313
314
	public List<JTextField> findTextFields() {
315
		List<JTextField> fields = new LinkedList<>();
316
317
		Component[] children = headerPanel.getComponents();
318
		// this is your 'search-loop':
319
		for (Component child : children) {
320
			if (child instanceof JTextField) {
321
				JTextField childField = (JTextField) child;
322
				name = childField.getName();
323
				if (name.startsWith(nameTField)) {
324
					fields.add(childField);
325
				}
326
			}
327
		}
328
329
		return fields;
330
	}
331
332
public static final Pattern POSTFIX_PATTERN = Pattern.compile(nameTField + "(\\d+)");
333
334
JSpinner
335
336
    spinner = new JSpinner();
337
	spinner.addContainerListener(new ContainerAdapter() {
338
		@Override
339
		public void componentAdded(ContainerEvent arg0) {
340
			boxesRemoved();
341
			boxesChanged();
342
			}
343
	});
344
	spinner.addChangeListener(new ChangeListener() {
345
		public void stateChanged(ChangeEvent arg0) {
346
			int spinnerValue = (Integer) spinner.getValue();
347
			if (spinnerValue == headerPanel.getComponentCount()) {
348
				System.out.println("Error, spinner shouldn't change to same value");
349
			}
350
351
			if (spinnerValue < headerPanel.getComponentCount()) {
352
				boxesRemoved();
353
    			frame.revalidate();
354
				frame.repaint();
355
			}
356
357
			while (spinnerValue > headerPanel.getComponentCount()) {
358
				boxesChanged();
359
360
				// frame.getContentPane().add(tField);
361
				frame.revalidate(); // For JDK 1.7 or above.
362
				// frame.getContentPane().revalidate(); // For JDK 1.6 or below.
363
				frame.repaint();
364
			}
365
		}
366
	});
367
368
boxesRemoved() method
369
370
	public void boxesRemoved() {
371
		for (JTextField textField : findTextFields()) {
372
			String name = textField.getName();
373
			Matcher matcher = POSTFIX_PATTERN.matcher(name);
374
			if (matcher.matches()) {
375
				String strPostfix = matcher.group(1);
376
				int postFixNumeric = Integer.parseInt(strPostfix);
377
378
				System.out.println("for postFix = " + postFixNumeric + ": " + textField.getText());
379
				if (postFixNumeric < findTextFields().size()) {
380
					System.out.println("PFN: " + postFixNumeric);
381
					System.out.println("FTF: " + findTextFields().size());
382
					findTextFields().remove(findTextFields().size() - 1);
383
					headerPanel.remove(findTextFields().size() - 1);
384
				}
385
			}
386
		}
387
	}
388
389
390
boxesChanged() method
391
392
	public void boxesChanged() {
393
		int hp = headerPanel.getComponentCount();
394
395
		tField = new JTextField();
396
		tField.setName(nameTField + hp);
397
		textFieldList.add(tField);
398
399
		tField.getDocument().addDocumentListener(new DocumentListener() {
400
401
			public void changedUpdate(DocumentEvent e) {
402
				warn();
403
			}
404
405
			public void removeUpdate(DocumentEvent e) {
406
				warn();
407
			}
408
409
			public void insertUpdate(DocumentEvent e) {
410
				warn();
411
			}
412
413
			public void warn() {
414
415
				int digits = 1;
416
417
				if (hp > 9) {
418
					digits = 2;
419
				}
420
421
				String getFieldString;
422
				int getFieldNum;
423
424
				getFieldString = tField.getName().substring(tField.getName().length() - digits);
425
426
				getFieldNum = Integer.parseInt(getFieldString);
427
428
				headerData = new Object[hp + 1];
429
430
				for (JTextField textField : findTextFields()) {
431
					Matcher matcher = POSTFIX_PATTERN.matcher(name);
432
					System.out.println(name);
433
					if (matcher.matches()) {
434
						String strPostfix = matcher.group(1);
435
						int postfixNumeric = Integer.parseInt(strPostfix);
436
437
						System.out.println("for postfix = " + postfixNumeric + ": " + textField.getText());
438
					} else {
439
						System.out.println("matcher error: " + matcher);
440
					}
441
				}
442
			}
443
		});
444
445
		headerPanel.add(tField);
446
447
	}