如何从JFrame获取文本

时间:2012-08-17 01:36:04

标签: java swing jframe jtextfield

我正在学习java,我有一个小问题, 我试图从Jtextfield获取“文本”,但它是空的。 更具体一点。

我有一个JFrame,其中是界面和JTextfield,还有一个名为“save”的按钮,当我按下save时会打开一个包含操作的类(写入属性文件),问题是当我尝试直接从这个类从文本字段中获取文本我得到“没有 - 空”我尝试了System.out.print();但我没有得到任何东西......如果我使用variable.getText()从JFrame打印;它变得正确,我尝试使用getter和setter并尝试直接从变量中获取,例如:

    JFrame obj = new JFrame();
    String variable = obj.txt_jtextfield.getText();

没有成功,这基本上就是代码:

按钮:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    db_connection_modifier obj = new db_connection_modifier();
    obj.hostconfig();
    //System.out.println("Conexion: "+txt_ip.getText()+"\n"+txt_db.getText()+"\n"+txt_user.getText()+"\n"+txt_pass.getText());
} 

这是方法:

public void hostconfig(){
        dbconfig_manager obj1 = new dbconfig_manager();        
        String ip = obj1.txt_ip.getText();
        String db_name = obj1.txt_db.getText();
        String user = obj1.txt_user.getText();
        String password = obj1.txt_pass.getText();
        System.out.println("DATA:  " + dbconfig_manager.txt_ip.getText() + "\n" +dbconfig_manager.txt_db.getText() + "\n" + user + "\n" + password);
}

我变空了,我不知道是不是因为“按钮”,我对“新”命令不太了解

提前致谢:)

编辑:

这是完整的课程:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clases;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import interfaz.*;
import java.io.FileInputStream;
import java.util.Enumeration;

/**
 *
 * @author TheCoder
 */
public class db_connection_modifier {

    public void hostconfig() {

        Properties prop = new Properties();
        dbconfig_manager obj1 = new dbconfig_manager();
        String ip = obj1.txt_ip.getText();
        String db_name = obj1.txt_db.getText();
        String user = obj1.txt_user.getText();
        String password = obj1.txt_pass.getText();
        System.out.println("INFO:  " + dbconfig_manager.txt_ip.getText() + "\n" + dbconfig_manager.txt_db.getText() + "\n" + user + "\n" + password);

        FileInputStream is = null;

        // Cargamos el fichero de propiedades
        try {
            // Asumimos que el fichero existe
            String path = getClass().getResource("db_config.properties").getPath();
            //CARGAMOS EL ARCHIVO
            prop.load(new FileInputStream(path));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        // Listamos las propiedades
        System.out.println("PROPIEDADES POR DEFECTO");
        for (Enumeration e = prop.keys(); e.hasMoreElements();) {
            Object obj = e.nextElement();
            System.out.println(obj + ": "
                    + prop.getProperty(obj.toString()));
        }

        // Modificamos los valores
        prop.setProperty("db_ip", obj1.txt_ip.getText());
        prop.setProperty("db_name", obj1.txt_db.getText());
        prop.setProperty("Login_type", "");
        prop.setProperty("db_username", obj1.db_name);
        prop.setProperty("db_password", obj1.password);



        // Volvemos a listar los valores
        System.out.println("PROPIEDADES MODIFICADAS");
        for (Enumeration e = prop.keys(); e.hasMoreElements();) {
            Object obj = e.nextElement();
            System.out.println(obj + ": "
                    + prop.getProperty(obj.toString()));
        }


//        try {
//
//            Properties prop = new Properties();
//            dbconfig_manager obj = new dbconfig_manager();
//            String ip = obj.txt_ip.getText();
//            String db_name = obj.txt_db.getText();
//            String user = obj.txt_user.getText();
//            String password = obj.txt_pass.getText();   
//            
//            System.out.println("Conexion: "+ip+"\n"+db_name+"\n"+user+"\n"+password);
//           
//            prop.setProperty("db_ip", ip);
//            prop.setProperty("db_name", db_name);
//            
//            if (obj.cb_method.getSelectedIndex() == 0) {
//                prop.setProperty("Login_Type", "win_auth");
//                
//            } else if (obj.cb_method.getSelectedIndex() == 1) {
//                prop.setProperty("Login_Type", "manual_auth");
//                prop.setProperty("db_username", user);
//                prop.setProperty("db_password", password);
//
//                System.out.println("Paso por aqui!!!");
//                
//            }
//
//
//            //save properties to project root folder
//            String path = getClass().getResource("DB_configuration.properties").getPath();
//            prop.store(new FileOutputStream(path), null);             
//
//        } catch (IOException ex) {
//            System.out.println(ex);
//        }
    }
}

这是JFrame:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;
import clases.*;
import javax.swing.JComboBox;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
 *
 * @author TheCoder
 */
public class dbconfig_manager extends javax.swing.JFrame {

    /**
     * Creates new form dbconfig_manager
     */
    public dbconfig_manager() {
        initComponents();
//         mauth_panel.setVisible(false);

    }
    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        mauth_panel = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txt_user = new javax.swing.JTextField();
        txt_pass = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        cb_method = new javax.swing.JComboBox();
        txt_ip = new javax.swing.JTextField();
        txt_db = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(1024, 768));
        getContentPane().setLayout(null);

        jPanel1.setBackground(java.awt.Color.lightGray);
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setOpaque(false);

        jLabel2.setBackground(new java.awt.Color(255, 255, 255));
        jLabel2.setFont(new java.awt.Font("Lucida Sans", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Domain name(IP): ");

        jLabel3.setBackground(new java.awt.Color(255, 255, 255));
        jLabel3.setFont(new java.awt.Font("Lucida Sans", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Data base name: ");

        jLabel4.setBackground(new java.awt.Color(255, 255, 255));
        jLabel4.setFont(new java.awt.Font("Lucida Sans", 1, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Method: ");

        jLabel5.setText("Usuario: ");

        jLabel6.setText("Contraseña: ");

        javax.swing.GroupLayout mauth_panelLayout = new javax.swing.GroupLayout(mauth_panel);
        mauth_panel.setLayout(mauth_panelLayout);
        mauth_panelLayout.setHorizontalGroup(
            mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mauth_panelLayout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt_user)
                    .addComponent(txt_pass, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE))
                .addContainerGap(49, Short.MAX_VALUE))
        );
        mauth_panelLayout.setVerticalGroup(
            mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mauth_panelLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txt_user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mauth_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txt_pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(58, Short.MAX_VALUE))
        );

        jButton1.setText("Guardar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Borrar");

        cb_method.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "win_auth", "manual_auth" }));
        cb_method.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_methodActionPerformed(evt);
            }
        });

        jButton3.setText("jButton3");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(mauth_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txt_ip))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(cb_method, 0, 200, Short.MAX_VALUE)
                                .addComponent(txt_db)))))
                .addContainerGap(50, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(77, 77, 77))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txt_ip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txt_db, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cb_method, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(46, 46, 46)
                .addComponent(mauth_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(25, 25, 25))
        );

        getContentPane().add(jPanel1);
        jPanel1.setBounds(300, 110, 450, 390);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/stretched-38776.jpg"))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 1024, 768);

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        db_connection_modifier obj = new db_connection_modifier();
        obj.hostconfig();
        //System.out.println("Conexion: "+txt_ip.getText()+"\n"+txt_db.getText()+"\n"+txt_user.getText()+"\n"+txt_pass.getText());
    }                                        


    private void cb_methodActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if (cb_method.getSelectedIndex() == 0) {
            System.out.println("win_auth: " + cb_method.getSelectedIndex());
            mauth_panel.setVisible(false);

        } else if (cb_method.getSelectedIndex() == 1) {
            System.out.println("manual_auth: " + cb_method.getSelectedIndex());
            mauth_panel.setVisible(true);
        }
    }                                         

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       System.out.println("Obteniendo datos:   " + txt_ip.getText() + "\n" + txt_db.getText()
               + "\n" + txt_user.getText() + "\n" + txt_pass.getText());
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        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(dbconfig_manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dbconfig_manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dbconfig_manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dbconfig_manager.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 dbconfig_manager().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    public javax.swing.JComboBox cb_method;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel mauth_panel;
    public static javax.swing.JTextField txt_db;
    public static javax.swing.JTextField txt_ip;
    public static javax.swing.JPasswordField txt_pass;
    public static javax.swing.JTextField txt_user;
    // End of variables declaration
}

正如我之前所说的......当我尝试时,我只是“空”:

    System.out.println("INFO:  " + ip + "\n" + db_name + "\n" + user + "\n" + password);

2 个答案:

答案 0 :(得分:4)

因此JFrame没有名为txt_jtextfield

的方法或属性

不知道你是如何构建这个JFrame的,因此很难知道建议什么。

假设你做了类似......

的事情
JText txt_jtextfield = new JTextField();
JFrame obj = new JFrame();
// Some other initialisation code...
obj.add(txt_jtextfield);

您应该能够直接获得该值。

如果该字段存在于其“自己的”框架中。您应该直接创建父框架

FrameWithTextFieldInIt obj = new FrameWithTextFieldInIt();
// etc...

然后由框架提供对该字段的访问(通过将其公开,或者更优选地,通过获取者)

您确实需要提供有关文本字段存在位置以及您尝试访问它的上下文的更多信息

<强>已更新

您不能以这种方式使用JFrame

dbconfig_manager obj1 = new dbconfig_manager();
String ip = obj1.txt_ip.getText();

基本上是说,“让我成为一个框架,并在你完成后继续运行”。这意味着,文本字段中没有任何内容。

两个选项。

  1. 请改用模式JDialog,参见How to make Dialogs
  2. 改变你的工作流程。
  3. 而不是db_connection_modifier类负责显示UI,使其仅负责更新属性并使用某种“更新”按钮创建配置框架,该按钮将调用db_connection_modifier

    <强>更新

    Max也是正确的,在你是“Guardar”按钮的动作处理程序中,你正在这样做......

    db_connection_modifier obj = new db_connection_modifier();
    obj.hostconfig();
    

    正在创建一个全新的dbconfig_manager,其中没有详细信息。您应该直接将属性传递给它...

    db_connection_modifier obj = new db_connection_modifier(txt_ip.getText(), txt_db.getText(), txt_user.getText(), txt_pass.getText());
    obj.hostconfig();
    

    这会将您的UI与应用程序逻辑分离

答案 1 :(得分:3)

看起来db_connection_modifier创建dbconfig_manager的新实例,而不是使用现有框架。要解决问题,请将现有框架的实例传递给dbconfig_manager。最好将连接参数包装到一个类中,然后传递这个类。