How can I insert the i value into the variable? - java

I have 5 textFields and they are in sequence book1TextField, book2TextField.book3.,book4.,book5. I want variable i to be inserted in these textFields so it will be like book(i)TextField.getText() so that I don't have to do this one by one.
for (int i = 0; i < 5; i++){
bookQuantities[i] = Integer.parseInt(book1TextField.getText());
System.out.println(bookQuantities[i]);
}

When those TextFields are created you should store them in an ArrayList<TextField> to be accessed at a later time. Then you can easily write something like:
for(int i = 0; i < bookTextFields.size(); i++) {
bookQuantities[i] = Integer.parseInt(bookTextFields.get(i).getText());
}

You can use instanceof like this:
int comp = panel.getComponentCount();
int[] bookQuantities = new int [comp];
for (int i = 0; i < comp; i++) {
if (panel.getComponent(i) instanceof JTextField) {
JTextField txt = (JTextField) panel.getComponent(i);
bookQuantities[i] = Integer.parseInt(txt.getText());
System.out.println(bookQuantities[i]);
}
}

Related

Data assigned to new multidimensional array keeps updating

sorry I don't know how title this question but I am having an issue with assigning data to a new multidimentional array, do something and then retrieve the old data.
In my case I am trying to loop through JTextFields, assign all current data specifically the colour to a new multidimentional array. Then I want to do a search and change the background colour of found textfields.
Now I have a reset button that I would like the old colours that are now in the new multidimentional array to be assigned back to the fields. The issue I am having is that the new multidimentional array has updated after the search with the new colours. I really appreciate if someone can point me to the right direction.
Here is my code:
public JTextField[][] fields = new JTextField[totalX][totalY];
public JTextField[][] newFields = new JTextField[totalX][totalY];
if (e.getSource() == btnFind || e.getSource() == txtSearch)
{
// Make a copy of fields before selecting everything
for(int t = 0; t < totalX; t++){
for(int r = 0; r < totalY; r++){
newFields[t][r] = fields[t][r];
}
}
findStudentRecord();
// when looping though newFields[x][y] here it is already updated to the current colour
}
if (e.getSource() == btnReset)
{
for(int x = 0; x < totalX; x++){
for(int y = 0; y < totalY; y++){
fields[x][y].setText(newFields[x][y].getText());
fields[x][y].setBackground(newFields[x][y].getBackground());
// have tried this one but doesn't work
if(newFields[x][y].getBackground() == Color.green){
fields[x][y].setBackground(Color.green);
System.out.print(fields[x][y].getText() + "\n");
}
}
}
}
Here is the findStudentRecord()
public void findStudentRecord()
{
boolean found = false;
String strFind = txtSearch.getText();
for(int x = 0; x < totalX; x++){
for(int y = 0; y < totalY; y++){
if(fields[x][y].getText().equalsIgnoreCase(strFind))
{
found = true;
}
}
}
if (found)
{
for (int x = 0; x < totalX; x++)
{
for(int y = 0; y < totalY; y++){
if(fields[x][y].getText().equalsIgnoreCase(strFind))
{
fields[x][y].setBackground(new Color(255,217,200));
}
}
}
txtSearch.setText(txtSearch.getText() + " ...Found.");
}
else
{
txtSearch.setText(txtSearch.getText() + " ...Not Found.");
}
}
You have to create a new JTextField and add the relevant data:
newFields[t][r] = new javax.swing.JTextField();
newFields[t][r].setText(fields[t][r].getText());
newFields[t][r].setColumns(fields[t][r].getColumns());
// any other property you want to transfer

Two dimension array, how to programically add new array element? Java

I don't know, if I forgot how, or I just can't figure it out how.
For example :
Object[][] data = {
{"id", "projectname","valueid", "value"},
};
And this is how they should be added, but in loop:
Object[][] data = {
{"id", "projectname","valueid", "value"},
{"id2", "projectname2","valueid2", "value2"},
{"id3", "projectname3","valueid3", "value3"},
};
And so on..
I need a tip only, like a skeleton how it should be. I tried to figure it out, but had no idea how.
Thanks!
You can add a new array to another array like this :
data[1] = new Object[]{"id_1", "projectname_1","valueid_1", "value_1"};
...
data[n] = new Object[]{"id_n", "projectname_n","valueid_n", "value_n"};
You can use this way in any loop for example :
int length = 5;
Object[][] data = new Object[length][];
for(int i = 0; i < length; i++){
data[i] = new Object[]{...some information};
}
for (int i = 1; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
int line = i+1;
data[i][j] = data[0][j]+ line;
}
}

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a JTable. I tried Arrays.toString(myTwoDimensionalArrayVariable) but it won't display the string values.
My goal is to check duplicates for every column per row of a destination JTable when user tries to add row values from a source JTable that's why I want to display the contents of the array.
The values on columns are combination of double, String, and int.
int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];
for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}
System.out.println(Arrays.toString(myRowValues));
if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}
I only get this output:
run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;#35fa3ff2]
[[Ljava.lang.Object;#407c448d, [Ljava.lang.Object;#1e78a60e]
Is there any other alternative than using 2 Dimensional Arrays?
I'd appreciate any help.
Thanks.
IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().
EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:
List<List<Object>> objectList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
objectList.add(j, new ArrayList<>());
for (int i = 0; i < 2; i++) {
if (i==0) objectList.get(j).add("string" + j + i);
if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
}
}
System.out.println("OBJECT LIST: "+objectList);
Output:
OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]
Your code should look like this, then:
List<List<Object>> myRowValues = new ArrayList<>();
for (int j = 0; j < myRowCount; j++) {
myRowValues.add(j, new ArrayList<>());
for (int i = 0; i < myColumnCount; i++) {
myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
}
}
System.out.println(myRowValues);

JTextField Array issue

So I'm working with a two-dimensional array of JTextFields for a Sudoku program.
public JTextField[][] userInputArray = new JTextField[9][9];
Now. I'm getting a continual null pointer exception, and can't discern how to fix it. It comes from firing this method:
public void showTextFields()
{
int rowCounter = 0;
int columnCounter = 0;
for (rowCounter = 0; rowCounter <= 8; rowCounter += 1)
{
for (columnCounter = 0; columnCounter <= 8; columnCounter += 1)
{
pane.setLayout(new GridLayout(9, 9));
//pane.add(userInputArray[rowCounter][columnCounter]);
//userInputArray[rowCounter][columnCounter].setColumns(1);
//userInputArray[rowCounter][columnCounter].setVisible(true);
}
}
}
Everything commented out will throw the nullpointerexception.
Optimally, my goal is to display the JTextFields on screen, assigning them on the grid.
NullPointerException occurs at pane.add(...)
While you have created the 2D array to house your fields, you need to instantiate the JTextField components in your array.
for (int i =0; i < userInputArray.length; i++) {
for (int j =0; j < userInputArray[0].length; j++) {
userInputArray[i][j] = new JTextField();
}
}
When you declare array it is initialized with default values. Default value for Object is null so you need to instantiate the objects first before using them
userInputArray[rowCounter][columnCounter] = new JTextField();
So now your code should look like below
for (columnCounter = 0; columnCounter <= 8; columnCounter += 1)
{
pane.setLayout(new GridLayout(9, 9));
userInputArray[rowCounter][columnCounter] = new JTextField();
pane.add(userInputArray[rowCounter][columnCounter]);
userInputArray[rowCounter][columnCounter].setColumns(1);
userInputArray[rowCounter][columnCounter].setVisible(true);
}

Clear Two Dimensional Array

How can I clear a 6x6 "table", so that anything in it is cleared?
(I made the clearbutton already with ActionListener...etc)
//other code above that creates window, below is the code that creates the table I need to clear
square = new JTextField[s][s];
for (int r=0; r!=s; r++) {
symbols[r] = new JTextField();
symbols[r].setBounds(35+r*35, 40, 30, 25);
win.add(symbols[r], 0);
for (int c=0; c!=s; c++) {
square[r][c] = new JTextField();
square[r][c].setBounds(15+c*35, 110+r*30, 30, 25);
win.add(square[r][c], 0);
}
}
win.repaint();
}
Loop over the array and and set each element to null. You can use the java.utils.Arrays utility class to make things cleaner/neater.
for( int i = 0; i < square.length; i++ )
Arrays.fill( square[i], null );
Here is one line solution:
Arrays.stream(square).forEach(x -> Arrays.fill(x, null));
Something like...
for (int index = 0; index < square.length; index++) {
square[index] = null;
}
square = null;
Will do more then the trick (in fact the last line would normally be enough)...
If you're really paranoid...
for (int index = 0; index < square.length; index++) {
for (int inner = 0; inner < square[index].length; inner++) {
square[index][inner] = null;
}
square[index] = null;
}
square = null;

Categories