Chamar outra tela apartir de um JFrame no j2ME

1 resposta
T

possuo o seguinte codigo:

package com;

import com.utils.FileUtils;
import com.wrapper.Cliente;
import javax.swing.JOptionPane;


/**
 * @author tiago


 */
public class FrameCliente extends javax.swing.JFrame {
    public Cliente cliente = new Cliente();
    static {
       try {           
//           javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
       } catch(Exception exception) {
           System.out.println("Error loading L&F: " + exception);
       }        
    }

    /** Creates new form NewJFrame */
    public FrameCliente() {
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        //NSIcom won't close app without this
        this.addWindowListener(new java.awt.event.WindowAdapter() {
	    public void windowClosing(java.awt.event.WindowEvent e) {System.exit(0);}
	});
        // </editor-fold>                       
        initComponents();
//        if (cliente!=null){
//            setCliente(cliente);
//            System.out.println("SETOU CLIENTE...");
//        }

    }

    private void setCliente(Cliente cliente){
        jTextField_Nome.setText(cliente.nome);
        jTextField_Endereco.setText(cliente.endereco);
        jTextField_Telefone.setText(cliente.telefone);
    }

    private boolean valida(){
        if (jTextField_Nome.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Nome deve ser inserido");
            return false;
        }
        if (jTextField_Endereco.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Endereco deve ser inserido");
            return false;
        }
        if (jTextField_Telefone.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Telefone deve ser inserido");
            return false;
        }

        return true;
    }

    private void salvar(){
        try {
            if (valida()){
                String cliente = new String();
                cliente = jTextField_Nome.getText() + "$" + jTextField_Endereco.getText() + "$" +
                jTextField_Telefone.getText() + "$" + "N$" + "N$\n";

                System.out.println("Nome: "+jTextField_Nome.getText());
                System.out.println("Endereco: "+jTextField_Endereco.getText());
                System.out.println("Telefone: "+jTextField_Telefone.getText());
                System.out.println("Enviado: N");
                System.out.println("Deletar: N");
                System.out.println(cliente.toString());

                FileUtils.salvarArquivoTexto("arquivoTeste", cliente.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jTextField_Nome = new javax.swing.JTextField();
        jLabel_Nome = new javax.swing.JLabel();
        jTextField_Endereco = new javax.swing.JTextField();
        jLabel_Endereco = new javax.swing.JLabel();
        jLabel_Telefone = new javax.swing.JLabel();
        jTextField_Telefone = new javax.swing.JTextField();
        jToggleButton_Salvar = new javax.swing.JToggleButton();
        jToggleButton_Fechar = new javax.swing.JToggleButton();
        jSeparator1 = new javax.swing.JSeparator();

        jTextField1.setText("jTextField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        jLabel_Nome.setText("Nome:");
        jLabel_Nome.setPreferredSize(new java.awt.Dimension(40, 14));

        jLabel_Endereco.setText("Endereço:");
        jLabel_Endereco.setPreferredSize(new java.awt.Dimension(40, 14));

        jLabel_Telefone.setText("Telefone:");
        jLabel_Telefone.setPreferredSize(new java.awt.Dimension(40, 14));

        jToggleButton_Salvar.setText("Ok");
        jToggleButton_Salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton_SalvarActionPerformed(evt);
            }
        });

        jToggleButton_Fechar.setText("Fechar");
        jToggleButton_Fechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton_FecharActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel_Telefone, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
                    .add(jLabel_Endereco, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
                    .add(jLabel_Nome, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField_Nome)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField_Endereco)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField_Telefone, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE))
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(65, 65, 65)
                .add(jToggleButton_Salvar)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jToggleButton_Fechar)
                .addContainerGap(296, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField_Nome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel_Nome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField_Endereco, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel_Endereco, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField_Telefone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel_Telefone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 50, Short.MAX_VALUE)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jToggleButton_Fechar)
                    .add(jToggleButton_Salvar))
                .add(31, 31, 31))
        );

        pack();
    }// </editor-fold>                        

    private void jToggleButton_FecharActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        System.exit(0);
    }                                                    

    private void jToggleButton_SalvarActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        salvar();
    }                                                    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrameCliente().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel_Endereco;
    private javax.swing.JLabel jLabel_Nome;
    private javax.swing.JLabel jLabel_Telefone;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField_Endereco;
    private javax.swing.JTextField jTextField_Nome;
    private javax.swing.JTextField jTextField_Telefone;
    private javax.swing.JToggleButton jToggleButton_Fechar;
    private javax.swing.JToggleButton jToggleButton_Salvar;
    // End of variables declaration                   

}
package com;

import com.utils.FileUtils;
import com.utils.MyTableModel;
import com.utils.MyTableSorter;
import com.wrapper.Cliente;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

/**
 * @author tiago


 */
public class FrameCliente_Ler extends javax.swing.JFrame {

    static {
        try {
//           javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception exception) {
            System.out.println("Error loading L&F: " + exception);
        }
    }

    /** Creates new form NewJFrame */
    public FrameCliente_Ler() {
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        //NSIcom won't close app without this
        this.addWindowListener(new java.awt.event.WindowAdapter() {
	    public void windowClosing(java.awt.event.WindowEvent e) {System.exit(0);}
	});
        // </editor-fold>                       
        initComponents();
    }


    /** Método que inicializa a tela. */
    private void initTabelaClientes() {
        // Se columnCount > 0 é pq já inicializou...
        if (jTable_Cliente.getColumnCount() > 0) {
            return;
        }

        // Definindo as colunas...
        MyTableModel tm = new MyTableModel();
        tm.addColumn("Nome");
        tm.addColumn("Endereco");
        tm.addColumn("Telefone");
        tm.addColumn("Enviado");
        tm.addColumn("Deletar");
        tm.addColumn("Obj");

        // Definindo a ordenação...
        MyTableSorter ts = new MyTableSorter(tm);
        jTable_Cliente.setModel(ts);
        ts.setTableHeader(jTable_Cliente.getTableHeader());

        // Definindo a largura das colunas...
        jTable_Cliente.getColumn("Nome").setPreferredWidth(100);
        jTable_Cliente.getColumn("Endereco").setPreferredWidth(100);
        jTable_Cliente.getColumn("Telefone").setPreferredWidth(50);
        jTable_Cliente.getColumn("Enviado").setPreferredWidth(20);
        jTable_Cliente.getColumn("Deletar").setPreferredWidth(20);

        // Removendo a coluna do objeto da view...
        jTable_Cliente.removeColumn(jTable_Cliente.getColumn("Obj"));

        // Inicializando o listener...
        javax.swing.ListSelectionModel lsm = jTable_Cliente.getSelectionModel();
        lsm.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            public void valueChanged(javax.swing.event.ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }

                javax.swing.ListSelectionModel lsm = (javax.swing.ListSelectionModel) e.getSource();
                if (!lsm.isSelectionEmpty()) {
                    int row = lsm.getMinSelectionIndex();
                    int col = jTable_Cliente.getModel().getColumnCount() - 1;
                    Cliente cliente = (Cliente) jTable_Cliente.getModel().getValueAt(row, col);
                    setCliente(cliente);
                }
            }
        });
    }

    private void setCliente(Cliente cliente){
        new FrameCliente().setVisible(true);
        System.out.println("SET_CLIENTE.......");

    }

    /** Método que atualiza a consulta atual. */
    public void atualizarTabelaOrcamentoDespesa() {
        /** valorTotalCombustiveis = 0; */
//        SwingUtils.iniciarProcesso(this);
        try {
            initTabelaClientes();

            MyTableSorter ts = (MyTableSorter) jTable_Cliente.getModel();
            ts.reset();
//            if (cliente == null) {
//                return;
//            }
//            OrcamentoDespesaSC filtro = new OrcamentoDespesaSC();
//            filtro.orcamento = orcamento;
            ArrayList lista = null;
            lista = ler();

            for (int i = 0; i < lista.size(); i++) {
                Cliente cliente = (Cliente) lista.get(i);
                Object[] row = new Object[6];
                row[0] = cliente.nome;
                row[1] = cliente.endereco;
                row[2] = cliente.telefone;
                row[3] = cliente.enviado;
                row[4] = cliente.deletar;
                row[5] = cliente;
                ts.addRow(row);

            }

        } catch (Exception ex) {
//            Msg.alert(this, "Erro ao carregar tabela: ", ex);
        } finally {
//            SwingUtils.finalizarProcesso(this);
        }


    }


    private ArrayList ler() {
        ArrayList clientes = new ArrayList();

        try {
            String Nome, Endereco, Telefone, Enviado = new String();
            String cliente = FileUtils.abrirArquivoTexto("arquivoTeste");


            BufferedReader in = null;
            String linha = null;
            try {
                int linha_atual = 1;
                //int linhas = contarLinhas(file);
                int codigoPessoa = 774;

                in = new BufferedReader(new FileReader("arquivoTeste"));
                while ((linha = in.readLine()) != null) {
                    linha_atual++;
                    codigoPessoa++;

                    StringTokenizer st2 = new StringTokenizer(linha, "$");

                    String nome = "";
                    String endereco = "";
                    String telefone = "";
                    String enviado = "";
                    String deletar = "";

                    int i = 0;
                    boolean incluir = true;
                    while (st2.hasMoreTokens()) {
                        String s = st2.nextToken();
                        i++;

                        switch (i) {
                            case 1:
                                nome = s.trim();
                            case 2:
                                endereco = s.trim();
                            case 3:
                                telefone = s.trim();
                            case 4:
                                enviado = s.trim();
                            case 5:
                                deletar = s.trim();
                        }
                    }

                    Cliente cliente1 = new Cliente();
                    cliente1.nome = nome;
                    cliente1.endereco = endereco;
                    cliente1.telefone = telefone;
                    cliente1.enviado = enviado;
                    cliente1.deletar = deletar;
                    String addCliente = nome + endereco + telefone + enviado + deletar;

                    System.out.println(addCliente + "\n");

                    clientes.add(cliente1);

                }
            } finally {
                in.close();
            }

//            return clientes;

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }

        return clientes;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jToggleButton_Carregar = new javax.swing.JToggleButton();
        jToggleButton_Fechar = new javax.swing.JToggleButton();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_Cliente = new javax.swing.JTable();

        jTextField1.setText("jTextField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        jToggleButton_Carregar.setText("Carregar");
        jToggleButton_Carregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton_CarregarActionPerformed(evt);
            }
        });

        jToggleButton_Fechar.setText("Fechar");
        jToggleButton_Fechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton_FecharActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jTable_Cliente);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(65, 65, 65)
                .add(jToggleButton_Carregar)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jToggleButton_Fechar)
                .addContainerGap(316, Short.MAX_VALUE))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jToggleButton_Carregar)
                    .add(jToggleButton_Fechar))
                .add(21, 21, 21))
        );

        pack();
    }// </editor-fold>

    private void jToggleButton_FecharActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        System.exit(0);
    }                                                    

    private void jToggleButton_CarregarActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        atualizarTabelaOrcamentoDespesa();
    }                                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FrameCliente_Ler().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable_Cliente;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton_Carregar;
    private javax.swing.JToggleButton jToggleButton_Fechar;
    // End of variables declaration
}

E preciso criar uma tela de menu que chame as duas, tentei chamar a tela FrameCliente através da FrameCliente_Ler no método setCliente() danado um new FrameCliente().setVisible(true);
e me retornou o seguinte erro
java.lang.UnsupportedOperationException: Cannot create more than one window per graphics device

que não é possivel criar mais uma windows grafica.

oque eu faço ???

1 Resposta

WendersonLP

Bem, recentemente fiz um programa que chamava várias outras janelas, tipo JFrame, a acada ação de um botão da janela principal eu criava um objeto instanciava-o e a janela abria.

public void actionjButtonActionPerformed(java.awt.event.ActionEvent evt) {
         NomeDoJFrame name = new NomeDoJFrame();
         name.setVisible(true);
}

Dessa maneira a minha aplicação funcionou corretamente!

Criado 21 de novembro de 2009
Ultima resposta 21 de nov. de 2009
Respostas 1
Participantes 2