从另一个方法中的方法获取变量

时间:2015-05-12 02:24:58

标签: java methods

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controle_financeiro;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author IAGO
 */

public class TelaCadastroCategoria extends javax.swing.JFrame {

    /**
     * Creates new form TelaCadastroCategoria
     */
    public TelaCadastroCategoria() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nomeCategoria = new javax.swing.JTextField();
        botao_cadastra_tela_cadastro_categorias = new javax.swing.JButton();
        botao_voltar_tela_cadastro_categorias = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Nome da Categoria");

        nomeCategoria.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                nomeCategoriaMouseClicked(evt);
            }
        });

        botao_cadastra_tela_cadastro_categorias.setText("Cadastrar");
        botao_cadastra_tela_cadastro_categorias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botao_cadastra_tela_cadastro_categoriasMouseClicked(evt);
            }
        });

        botao_voltar_tela_cadastro_categorias.setText("Voltar");
        botao_voltar_tela_cadastro_categorias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botao_voltar_tela_cadastro_categoriasMouseClicked(evt);
            }
        });
        botao_voltar_tela_cadastro_categorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_voltar_tela_cadastro_categoriasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(76, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(botao_voltar_tela_cadastro_categorias, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botao_cadastra_tela_cadastro_categorias, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(nomeCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(74, 74, 74))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(nomeCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botao_cadastra_tela_cadastro_categorias, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botao_voltar_tela_cadastro_categorias, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25))
        );

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

    int var_id=1;

    private void botao_cadastra_tela_cadastro_categoriasMouseClicked(java.awt.event.MouseEvent evt) {                                                                     
     try {  

            String url = "jdbc:postgresql://localhost:5432/db_controle_financeiro";  
            String usuario = "us_iago";  
            String senha = "123";  

            Class.forName("org.postgresql.Driver");  

            Connection con;  

            con = DriverManager.getConnection(url, usuario, senha);  
            System.out.println("Conexão realizada com sucesso.");  
            Statement stm = con.createStatement(); 
            stm.executeUpdate("INSERT INTO categoria (id,nome) VALUES ('" + var_id + "','" + nome_categoria + "'");
            var_id++;


            con.close();  
        } catch (ClassNotFoundException | SQLException e) {  
            System.out.println("Problemas ao conectar ao banco.");
        }    
        TelaInicial tela_inicial_ccategoria = new TelaInicial();
        tela_inicial_ccategoria.setVisible(true);  
        dispose();
    }                                                                    


    private void nomeCategoriaMouseClicked(java.awt.event.MouseEvent evt) {                                           
         String nome_categoria = (nomeCategoria.getText()); 
    }                                          



    public static void main(String args[]) {


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaCadastroCategoria().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton botao_cadastra_tela_cadastro_categorias;
    private javax.swing.JButton botao_voltar_tela_cadastro_categorias;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JTextField nomeCategoria;
    // End of variables declaration                   
}

我正在使用java制作财务控制程序,但是我遇到了从另一个方法访问方法中的变量的问题。我如何从方法boto_cadastra_tela_cadastro_categoriasMouseClicked中的方法nomeCategoriaMouseClicked中获取变量nome_categoria?

1 个答案:

答案 0 :(得分:2)

您可以将变量设为实例变量。不要在任何方法中声明它,而是将声明/赋值放在顶部。然后你可以在那个班级的任何地方访问它。

public class TelaCadastroCategoria extends javax.swing.JFrame {
    String nome_categoria;
    // All the other code goes here
}

您可以在该类的任何方法中使用它。