How to pass an array to a Jtexfield?

Asked

Viewed 1,867 times

3

I’m doing a college paper where we have to do a kind of screen login, however, with array and not Arraylist.
My question is how I pass on the information from JTexfield to the array?

That one array needs to have the functions of adding a new student, delete and search and need to stay in another class, ie I will have a class with the graphical interface and another with the array and I want to call this array with all these functions that I mentioned earlier in my graphical interface.

My GUI code:

Main Class:

package pacote1;

import javax.swing.JFrame;

public class pricipal {

    public static void main(String[] args) {
        Janela janela = new Janela();

        janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        janela.setSize(550,300);
        janela.setVisible(true);
        janela.setLocationRelativeTo(null);
    }
}

Class of graphical interface:

package pacote1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javafx.scene.control.TextArea;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Janela extends JFrame  {

    private JTextField nomeField;
    private JTextField matriculaField;

    public Janela() {
        super("Nome da janela");

        criarFormulario();
    }

    private void criarFormulario() {
        JTextArea textarea;
        JButton button;
        JLabel label;

        setLayout(new BorderLayout());
        setLayout(new FlowLayout());

        JPanel panelTitulo = new JPanel();
        panelTitulo.setLayout(new  FlowLayout());

        JLabel titulo = new JLabel("");
        titulo.setFont(new Font("Verdana", Font.PLAIN, 16));

        panelTitulo.add(titulo);

        JPanel panelCadastro = new JPanel();
        panelCadastro.setLayout(new FlowLayout());

        JLabel nomeLabel = new JLabel("Nome");
        nomeField = new JTextField(15);

        JLabel matriculaLabel = new JLabel("Matricula");
        matriculaField = new JTextField(15);

        panelCadastro.add(nomeLabel);
        panelCadastro.add(nomeField);
        panelCadastro.add(matriculaLabel);
        panelCadastro.add(matriculaField);

        JPanel panelBotoes = new JPanel();
        panelBotoes.setLayout(new FlowLayout());

        Container c = getContentPane();
        c.setLayout(new FlowLayout(FlowLayout.CENTER));


        add(panelTitulo, BorderLayout.NORTH);
        add(panelCadastro, BorderLayout.CENTER);
        add(panelBotoes, BorderLayout.SOUTH);


    final JTextArea textArea;
    final JTextField texto;
    final JComboBox combo;
    JButton btn1,btn2,btn3,btn4,btn5;

       FlowLayout layout = new FlowLayout(FlowLayout.CENTER);
       FlowLayout JButton = new FlowLayout(FlowLayout.CENTER);
        c.setLayout(layout);
        c.setLayout(JButton);


        textArea = new JTextArea(4, 25);
        textArea.setLineWrap(true);

        JScrollPane spDescricao = new JScrollPane( textArea );
        this.getContentPane().add(spDescricao);



        //texto = new JTextField(10);
     String nomes[] = {"Ens.Médio","Universitário"};
       combo = new JComboBox(nomes);

       btn1 = new JButton("Novo aluno");
       btn2 = new JButton("Excluir aluno");
       btn3= new JButton("Consultar aluno");
       btn4 = new JButton("fechar");
       btn5 = new JButton("teste");
       btn1.addActionListener(
           new ActionListener(){
              public void actionPerformed(ActionEvent e){
                 textArea.append(nomeField.getText()); 
                 textArea.append(matriculaField.getText());
              }});
      btn4.addActionListener(
               new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                    System.exit(0);
              }}); 
     combo.addActionListener(
               new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                     //textArea.append(JComboBox.getSelectedItem()); 
            }});
    btn5.addActionListener(
               new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                     int i = 1;
                    //textArea.append(valores[i].toPrint());
         }});

       // c.add(texto);
        c.add(combo);
        c.add(btn1);
        c.add(btn2);
        c.add(btn3);
        c.add(btn4);
       c.add(btn5);
       c.add(textArea);
    }
}
  • Are you familiar with arrays operations? If not, here is good content that shows basic operations using an array: Arrays.

2 answers

4


Creating the array

JTextField array[] = new JTextField[100];

Each index of this array can store one JTexfield. Accesses normally work as in an integer array.

The "add a new student, delete and search" functions should be implemented as methods by the class that will handle the data from that array.

Follow an example:

import javax.swing.JTextField;

public class ArrayManip {

    private JTextField array[];

    public ArrayManip(int tamanho) {
        array = new JTextField[tamanho];
    }

    public void AcrescentarNovo(JTextField novo) {
        for (int x = 0; x < array.length; x++) {
            if (array[x] == null) {
                array[x] = novo;
                break;
            }
        }
    }
}

Accessing methods:

ArrayManip obj = new ArrayManip(100);
obj.AcrescentarNovo(new JTextField("Pessoa"));
  • And how will I connect this class with my name Jtextfield and enrollment?

  • There are several ways. The easiest way is to instantiate an Arraymanip object and access its methods from that object.

  • Can you give me an example based on my code?

  • I have attached to the reply.

  • I’ll study more about it, thank you very much.

1

You can solve it like this:

  1. Create a class, example: TrabalhoArray.java;

  2. In the class created in point 1 create an attribute, which will be a array the kind of objects you intend to handle, in this case, so I understand, JTextField;

  3. Create in this class the requested methods (add, delete, remove, etc);

  4. In your main class create an object of the type TrabalhoArray.java;

Example:

public class TrabalhoArray
{
     //o array de JTextField
     private JTextField[] array;

     //indice com a posicao do ultimo elemnto
     private int posAtual;

     //construtor sem parâmetros
     public TrabalhoArray()
     {
         //instancias o array com um tamanho padrão definido por ti
     }

     //contrutor que permite inicializar o array
     public TrabalhoArray(int dim)
     {
         array = new JTextField[dim];
     } 


     //método para adicionar um novo elemento ao array manipulando a posicao atual
     public void adicionar(JTextField arg)
     {
     }

     //metodo para remover um elemento
     public void remover(int pos)
     {
     }

     //Outros métodos que quiseres, como o pesquisar e etc.
}

Use:

...
public class Janela extends JFrame  {

   private TrabalhoArray teste = new TrabalhoArray(20); //exemplo com um array de 10 elementos    
   ...
}

This is an idea of how you can solve the problem. You could also create a generic class and indicate the data type as argument, but I found above simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.