Hot questions for Using JTextField in arraylist

Question:

I'm trying to check does inputed room number exist in array list:

private void initAction(RoomsWindow rw, RoomAddUpdateWindow raw) {
            btnConfirm.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    ArrayList<Room> rooms = RoomsWindow.loadRoom();
                    for (Room r : rooms) {
                        r.getNumber();
                    }
                    if (rooms.equals(txtNumber.getText())) {
                        JOptionPane.showMessageDialog(null, "Room number already exists!", "Add",
                                JOptionPane.PLAIN_MESSAGE);
                    } else {
                        File fileRooms = new File("src/txt/rooms");
                        try {
                            FileWriter fw = new FileWriter(fileRooms, true);
                            BufferedWriter bw = new BufferedWriter(fw);
                            PrintWriter pw = new PrintWriter(bw, true);
                            String tv = (String) cbTV.getSelectedItem();
                            if (cbTV.getSelectedItem().equals("Yes")) {
                                tv = "true";
                            } else {
                                tv = "false";
                            }
                            String miniBar = (String) cbMiniBar.getSelectedItem();
                            if (cbMiniBar.getSelectedItem().equals("Yes")) {
                                miniBar = "true";
                            } else {
                                miniBar = "false";
                            }
                            pw.println(txtNumber.getText() + "|" + txtType.getText() + "|" + txtName.getText() + "|"
                                    + txtBeds.getText() + "|" + tv + "|" + miniBar + "|" + "false" + "|" + "false");
                            pw.close();
                            JOptionPane.showMessageDialog(null, "Succesfully", "Done", JOptionPane.PLAIN_MESSAGE);
                            raw.setVisible(false);
                            rw.setVisible(false);
                            RoomsWindow newRoomWindow = new RoomsWindow();
                            newRoomWindow.setVisible(true);

                        } catch (IOException exc) {
                            exc.printStackTrace();
                        }
                    }
                }
            });
        }

If it exist then i don't want to write in file, just to print a message in

dialog: OptionPane.showMessageDialog(null, "Room number already exists!", "Add",
                                    JOptionPane.PLAIN_MESSAGE);

EDIT Here is my Room class: package entities;

public class Room {

    int number;
    String type;
    String name;
    int beds;
    Boolean tv;
    Boolean miniBar;
    Boolean ocupied;
    Boolean deleted;
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getBeds() {
        return beds;
    }
    public void setBeds(int beds) {
        this.beds = beds;
    }
    public Boolean getTv() {
        return tv;
    }
    public void setTv(Boolean tv) {
        this.tv = tv;
    }
    public Boolean getMiniBar() {
        return miniBar;
    }
    public void setMiniBar(Boolean miniBar) {
        this.miniBar = miniBar;
    }
    public Boolean getOcupied() {
        return ocupied;
    }
    public void setOcupied(Boolean ocupied) {
        this.ocupied = ocupied;
    }
    public Boolean getDeleted() {
        return deleted;
    }
    public void setDeleted(Boolean deleted) {
        this.deleted = deleted;
    }
    public Room(int number, String type, String name, int beds, Boolean tv, Boolean miniBar, Boolean ocupied,
            Boolean deleted) {
        super();
        this.number = number;
        this.type = type;
        this.name = name;
        this.beds = beds;
        this.tv = tv;
        this.miniBar = miniBar;
        this.ocupied = ocupied;
        this.deleted = deleted;
    }

}

Else, ofcourse, I want to write in file succesfuly. Where am I wrong?


Answer:

The "simplest" route would require you to loop over each Room in the rooms List and compare the roomNumber with the Room's room number

Something like...

List<Room> rooms = RoomsWindow.loadRoom();
// This may throw an exception, so you'll want to deal with that
String roomNumber = Integer.parseInt(txtNumber.getText());
boolean found = false;
for (Room room : rooms) {
    if (room.getNumber() == roomNumber) {
        found = true;
        break;
    }
}

nb: I don't have your Room class so I had to "guess" at it's functionality

A "sleeker" way might be to make use of the stream's API

Room match = rooms.stream().filter(room -> room.getNumber() == roomNumber).orElse(null);
if (match != null) {
    // Found room
} else {
    // Did not find foom
}

Question:

Hi I am working on an innovation in my company to handle the hits from the server so for that user has to add the service names in my application which is of monitoring application. So i have kept a button which will give the jtextfields counting to 9 so during submit button, how will i get the values from all the textboxes, below is my code,

package com.Lawrence;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Sample2 implements ActionListener
{
    JFrame mainFrame;
    static int count = 0;
    static int width_textfield = 10;
    static int height_textfield = 40;
    static int height = 0;
    JButton addTextField,submit;
    JTextField virtualDirectories;
    JLabel virtualDirectoriesName;
    ArrayList<String> texts = new ArrayList<String>();

    public Sample2()
    {
        mainFrame = new JFrame("Add Virtual Directory");
        mainFrame.setSize(640,640);
        mainFrame.setResizable(false);
        mainFrame.setLayout(null);

        addTextField = new JButton();
        addTextField.setText("Add Virtual directory");
        addTextField.setBounds(10, 10, 200, 25);
        addTextField.addActionListener(this);
        mainFrame.add(addTextField);

        submit = new JButton();
        submit.setText("Submit");
        submit.setBounds(180, 560, 100, 25);
        submit.addActionListener(this);
        mainFrame.add(submit);

        mainFrame.setVisible(true);

        height = mainFrame.getHeight();
    }
    public void actionPerformed(ActionEvent e) 
    {
        if(e.getActionCommand()== "Add Virtual directory")
        {
            if(height_textfield <= height-80)
            {
                virtualDirectoriesName = new JLabel("Virtual Directory"+"\t"+":");
                virtualDirectoriesName.setBounds(10,height_textfield,200, 25);
                mainFrame.add(virtualDirectoriesName);

                virtualDirectories = new JTextField();
                virtualDirectories.setBounds(150,height_textfield,200,25);
                mainFrame.add(virtualDirectories);

                texts.add(virtualDirectories.getText());

                count++;
                //width_textfield++;
                height_textfield = height_textfield+60;

                mainFrame.revalidate();
                mainFrame.repaint();

                //http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
            }
            else
            {
                JOptionPane.showMessageDialog(mainFrame, "can only add"+count+"virtual Directories");
            }
        }
        if(e.getActionCommand() == "Submit")
        {
            ArrayList<String> texts = new ArrayList<String>();
            for(int i = 0; i< count;i++)
            {
                texts.add(virtualDirectories.getText());
            }

            System.out.println(texts.size());
            System.out.println(texts.toString());
        }
    }
}

So i need to get the values from those textboxes and add it to an arraylist and then processing it to enter into my server for parsing the log files.So please explain me how to do it


Answer:

You could store every textfield into an arraylist, just like you did with the texts. Also, please take a look at how to use layout managers.

ArrayList<JTextField> fields = new ArrayList<JTextField>();

fields.add(virtualDirectories);

for (int i = 0; i < count; i++) {
    texts.add(fields.get(i).getText());
}

Edit:

This is a version of your code using layout managers. (plus the lines above, of course)

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Sample2 implements ActionListener {
    JFrame mainFrame;

    JPanel bottom;
    JPanel center;
    JPanel centerPanel1;
    JPanel centerPanel2;

    static int count = 0;
    static int width_textfield = 10;
    static int height_textfield = 40;
    static int height = 0;

    JButton addTextField, submit;
    JTextField virtualDirectories;
    JLabel virtualDirectoriesName;

    ArrayList<JTextField> fields = new ArrayList<JTextField>();
    ArrayList<String> texts = new ArrayList<String>();

    int maxFields = 10;

    public Sample2() {
        mainFrame = new JFrame("Add Virtual Directory");
        mainFrame.setSize(640, 640);
        mainFrame.setResizable(false);

        addTextField = new JButton();
        addTextField.setText("Add Virtual directory");
        addTextField.setBounds(10, 10, 200, 25);
        addTextField.addActionListener(this);

        submit = new JButton();
        submit.setText("Submit");
        submit.setBounds(180, 560, 100, 25);
        submit.addActionListener(this);

        center = new JPanel(new GridLayout(1, 2));

        centerPanel1 = new JPanel(new GridLayout(maxFields, 1, 0, 20));
        centerPanel2 = new JPanel();

        center.add(centerPanel1);
        center.add(centerPanel2);

        bottom = new JPanel(new FlowLayout());
        bottom.add(addTextField);
        bottom.add(submit);

        mainFrame.getContentPane().add(bottom, BorderLayout.SOUTH);
        mainFrame.getContentPane().add(center, BorderLayout.CENTER);
        mainFrame.setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand() == "Add Virtual directory") {

            if (count < maxFields) {

                JPanel p = new JPanel(new GridLayout(1, 2));

                virtualDirectoriesName = new JLabel("Virtual Directory" + "\t" + ":");
                virtualDirectories = new JTextField();

                p.add(virtualDirectoriesName);
                p.add(virtualDirectories);

                centerPanel1.add(p);

                texts.add(virtualDirectories.getText());
                fields.add(virtualDirectories);

                count++;
                // width_textfield++;
                height_textfield = height_textfield + 60;

                mainFrame.revalidate();
                mainFrame.repaint();

                // http://www.dreamincode.net/forums/topic/381446-getting-the-values-from-mutiple-textfields-in-java-swing/
            } else {
                JOptionPane.showMessageDialog(mainFrame, "can only add " + maxFields + " virtual Directories");
            }

        }
        if (e.getActionCommand() == "Submit") {
            ArrayList<String> texts = new ArrayList<String>();
            for (int i = 0; i < count; i++) {
                texts.add(fields.get(i).getText());
            }

            System.out.println(texts.size());
            System.out.println(texts.toString());
        }
    }

    public static void main(String[] args) {
        new Sample2();
    }

}

Question:

I have 2 lists displayed vertically in a JFrame. Lets say list A is an ArrayList<CustomTexField> and list B is an ArrayList<JLabel>.

I want to "update" the elements of list B that matches the same index of elements inside list A with the value from the CustomTextField.

I've tried adding document listener, but don't know how to calculate the index.

@Override
    public void insertUpdate(DocumentEvent e) {
        try {

            listB().get(INDEX).setText(e.getDocument().getText(0, e.getDocument().getLength()) + "");

        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }

    }

I have also created a method inside CustomTexField class that saves the index when its created but don't know how to 'read' it from e.getDocument()

EDIT: UPDATED TITLE


Answer:

If you're just trying to get the index of an item in an arraylist, you can just use the indexOf method.

int indexOfItem = arrayList.indexOf(itemIWant)

This is just how I interpreted your question but I would love clarification.

EDIT: If you're trying to get the object attached to the DocumentListener, you can check out this question: how to find source component that generated a DocumentEvent

Basically, if you have a DocumentListener for each CustomTextField, you can use the putProperty method described in the link to attach itself to it. From there, you can use getProperty(item) to find the item. You can do something similar with the index if you want but I believe that since you have an index field in your definition of CustomTextField, just attaching the CustomTextField with the DocumentListener will be enough.

//sometime on initalization of the lists
for(CustomTextField field: listA):
    field.getDocument().putProperty("owner", field);

...

@Override
public void insertUpdate(DocumentEvent e) {
    try {
        CustomTextField field = e.getDocument().getProperty("owner");
        int index = field.getIndex(); //assuming you have a getter method
        listB().get(index).setText(listA.get(index).getText());

    } catch (BadLocationException e1) {
        e1.printStackTrace();
    }

}

Question:

I have a panel that lists a set of JLabels based on items of an array. Also there is a JTextFiled and a JButton which work as a search tool.

So I could manage to compare the entered text with JLabels and highlight the matching JLabel. But what I want to do is to bring that JLabel to the top of the list. And when the search field is cleared, it goes back to its initial place.

Here is my code:

public class JavaApplication78 {

    JFrame frame;
    JPanel panel, labelsPanel, searchPanel;
    JLabel label;
    JTextField field;
    JButton button;
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<JLabel> labelsArray = new ArrayList<JLabel>();
    Border paddingBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
    Border border = BorderFactory.createLineBorder(Color.black);
    JScrollPane labelsScroll;

    public JavaApplication78() {
        frame = new JFrame();
        panel = new JPanel(new BorderLayout());
        names.add(".mp3");
        names.add(".html");
        names.add(".jpeg");
        names.add(".mp4");
        names.add(".pdf");

        labelsPanel = new JPanel(new GridBagLayout());
        listLabels();



        searchPanel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        field = new JTextField(10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 10;
        searchPanel.add(field, c);

        button = new JButton("Ser");
        c.weightx = 1;
        searchPanel.add(button, c);

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae) {
                String word = getText();
                for(JLabel label : labelsArray){
                    if (label.getText().equals(word)){
                        //labelsArray.add(0, labelsArray.get(i));
                        labelsArray.add(0, label);

                        label.setBackground(Color.red);
                    }
                }
            }
        });
        field.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                field.setText("");
                listLabels();
            }
        });

        panel.add(searchPanel, BorderLayout.NORTH);

        panel.add(labelsScroll, BorderLayout.CENTER);
        frame.add(panel);
        frame.setSize(200, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                new JavaApplication78();
            }
        });
    }
    public String getText(){
        return field.getText();
    }
    public void listLabels(){
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        labelsScroll = new JScrollPane(labelsPanel);
        for (String format : names) {
            label = new JLabel(format);
            //icon
            labelsArray.add(label);
            labelsPanel.add(label, gbc);
            label.setBorder(BorderFactory.createCompoundBorder(border, paddingBorder));
            label.setOpaque(true);
            label.setBackground(Color.white);
        }
    }    
}

Any idea how to bring the found JLabel to top of the list and put it back after search field is cleared ?


Answer:

Most layout managers will layout out components based on the order they are added, also known as z-order.

So you could use something like...

    field.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //Reset
            for (int order = 0; order < labelsArray.size(); order++) {
                JLabel label = labelsArray.get(order);
                labelsPanel.setComponentZOrder(label, order);
            }

            String text = field.getText();
            for (JLabel label : labelsArray) {
                if (label.getText().equals(text)) {
                    labelsPanel.setComponentZOrder(label, 0);
                    break;
                }
            }

            labelsPanel.revalidate();
            labelsPanel.repaint();
        }
    });

To re-order the labels based on the text entered into the field. This example resets the order based on the order the labels appear in the labelsArray, before trying to find a matching label

Question:

I made an ArrayList of arrays of JTextField. Now I want to get the value of the first position of the array that was previously stored in the ArrayList.

ArrayList <JTextField []> text_field;
text_field = new ArrayList <JTextField []> ();

I have tried doing this:

text_field.get (row)[column];

But this didn't work. How should I change it?

And how can I add the JTextField onto the panel?

for (int i = 0; i < text_field.size (); i++) {
  for (int j = 0; j < 8; j++) {

  }
}

Answer:

Try this:

((JTextField[]) text_field.get(row))[column];