java - 从一个方法访问另一个方法中的变量

标签 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制作一个财务控制程序,但是我在从另一个方法访问一个方法中的变量时遇到问题。我如何从方法 botao_cadastra_tela_cadastro_categoriasMouseClicked 中的方法 nomeCategoriaMouseClicked 访问变量 nome_categoria?

最佳答案

您可以将该变量设为实例变量。不要在任何方法中声明它,而是将声明/赋值放在顶部。然后您可以在该类中的任何位置访问它。

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

您将能够在该类的任何方法中使用它。

关于java - 从一个方法访问另一个方法中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180709/

相关文章:

java - 创建字符树

java - 与抽象类的继承混淆。方法会互相覆盖吗?

python-3.x - 如何在Python中获取方法名称

java - 导致应用程序崩溃的未知错误

java - 卡在添加到数组上

java - 线程 "main"java.lang.NoClassDefFoundError : com/beust/jcommander/ParameterException 中的异常

java - 如何在一个循环中找到数组中所有对之间的最大差异

java - 安卓屏幕

java - 如何让 TelegramBot 持续工作,而不需要一直手动启动我的 Java 程序?

java - 如何让标 checkout 现在面板中?