Tenho em uma tela, um array list que eu preencho dessa forma
ch = retornoSetor.toCharArray();
for (int i = 0; i < ch.length; i++){
switch (ch[i]) {
case '1':
listaSetor.add("Acadêmico");
break;
case '2':
listaSetor.add("Estágio");
break;
case '3':
listaSetor.add("Negociação");
break;
case '4':
listaSetor.add("Matrícula");
break;
}
}
Até ai tudo bem, consigo lista os itens do arraylist com um loop, ta funcionando.
Minha dificuldade é levar esse arraylist para uma outra tela e lista-lo.
Alguem pode me dizer uma maneira de fazer isso
Mas eu teria que criar algum metodo? essa é a minha dificuldade, quando estou na outra tela o construtor acha o arraylist mas pede para criar um metodo.
E é ai que esta meu problema, não estou conseguindo criar esse metodo
Eu conseguir passar o ArrayList com o costrutor ficou assim:
Na tela 1 fica o array list ok
Tela 1
public ArrayList listaSetor = new ArrayList();
telaBoasvindas(ArrayList lista) {
this.listaSetor = lista;
}
public telaBoasvindas() {
initComponents();
}
////////////////////////
ch = retornoSetor.toCharArray();
for (int i = 0; i < ch.length; i++){
switch (ch[i]) {
case '1':
listaSetor.add("Acadêmico");
break;
case '2':
listaSetor.add("Estágio");
break;
case '3':
listaSetor.add("Negociação");
break;
case '4':
listaSetor.add("Matrícula");
break;
}
JOptionPane.showMessageDialog(null, "setor"+listaSetor.get(i)); //verificando se arraylist ta preenchido
}
sóq eu não chega os itens na segunda tela.
Tela 2
private void BtnActionPerformed(java.awt.event.ActionEvent evt) {
final telaBoasvindas lista = new telaBoasvindas();
JOptionPane.showMessageDialog(null, "setor"+lista.listaSetor.get(0));
}
e da a seguinte exception:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
Simplesmente porque provavelmente seu Array está vazio e mesmo assim tu tenta realizar um get(i).
Faça o seguinte teste se não tem a garantia que o Array estará preenchido:
if (!suaLista.isEmpty()) {
// senão está vazio...
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author Expresso
*/
public class telaBoasvindas extends javax.swing.JFrame {
private static void listaSetor() {
throw new UnsupportedOperationException("Not yet implemented");
}
private JButton Iniciar;
private JLabel jLabel1;
private JLabel jLabel2;
private String setores;
private String setor;
public ArrayList listaSetor = new ArrayList();
public telaBoasvindas() {
initComponents();
}
//////-----------------------------------------------------/////////////////
telaBoasvindas(ArrayList lista) {
this.listaSetor = lista;
this.telaBoasvindas();// Aqui é pedido para criar um costrutor. e Ja existe um construtor
}
//////-----------------------------------------------------/////////////////
@SuppressWarnings("unchecked")
private void initComponents() {
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(atendimento.AtendimentoApp.class).getContext().getResourceMap(telaBoasvindas.class);
setBackground(resourceMap.getColor("Form.background")); // NOI18N
setBounds(new java.awt.Rectangle(0, 0, 400, 300));
setName("Form"); // NOI18N
jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(70, 70, 70)
.add(jLabel4))
.add(layout.createSequentialGroup()
.add(112, 112, 112)
.add(jLabel3)))
.addContainerGap(82, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap(139, Short.MAX_VALUE)
.add(jButton1)
.add(138, 138, 138))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(60, 60, 60)
.add(jLabel3)
.add(27, 27, 27)
.add(jLabel4)
.add(34, 34, 34)
.add(jButton1)
.addContainerGap(76, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Atendimento atende = new Atendimento();
//telaBoasvindas bvindas = new telaBoasvindas();
char ch [];
BufferedReader entrada = null;
Socket s = null;
PrintStream ps = null;
String ip = "";
InetAddress in = InetAddress.getLocalHost();
ip = in.getHostAddress();
// serividor prod 192.168.0.203
// serividor tst 192.168.0.215
//Cria o socket com o recurso desejado na porta especificada
s = new Socket("192.168.0.190",7000);
//Cria a Stream de saida de dados
ps = new PrintStream(s.getOutputStream());
//Imprime uma linha para a stream de saída de dados
ps.println("confere");
entrada = new BufferedReader(new InputStreamReader(s.getInputStream()));
String retornoSetor = entrada.readLine();
ch = retornoSetor.toCharArray();
for (int i = 0; i < ch.length; i++){
switch (ch[i]) {
case '1':
listaSetor.add("Acadêmico");
break;
case '2':
listaSetor.add("Estágio");
break;
case '3':
listaSetor.add("Negociação");
break;
case '4':
listaSetor.add("Matrícula");
break;
}
JOptionPane.showMessageDialog(null, "setor"+listaSetor.get(i));
}
//listaSetores(listaSetor);
// JOptionPane.showMessageDialog(null, retornoSetor);
atende.setVisible(true);
this.dispose();
s.close();
}catch(IOException e){
// JOptionPane.showMessageDialog(null, "Nome já em uso no atendimento");
System.out.println("Algum problema ocorreu ao criar ou enviar dados pelo socket."+e);
}finally{
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(telaBoasvindas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(telaBoasvindas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(telaBoasvindas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(telaBoasvindas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new telaBoasvindas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
// End of variables declaration
}
Na tela 2
é para aparece o item que foi escolhido, mas exception continua
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
final telaBoasvindas lista = new telaBoasvindas();
JOptionPane.showMessageDialog(null, "setor"+lista.listaSetor.get(0));
}