I'm learning java and I have a small problem, I'm trying to get "text" from a Jtextfield but it sents empty. To be more specific.
I have a JFrame where is the interface and the JTextfield and there's a button called "save", when I press save it opens a class that contains the operation (wrinting to a properties file), the problem is that when I try to get the text from the textfield directly from this class I get "nothing - empty" I tried to System.out.print(); but I get nothing... if I print from the JFrame with variable.getText(); it gets correctly, I tried with getters and setters and tried also getting directly from variable, for example:
JFrame obj = new JFrame();
String variable = obj.txt_jtextfield.getText();
no success, this is basically the code:
Button:
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());
}
This is the method:
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);
}
I get empty, I don't know if it because of "Button", I don't understand very well about the "new" command
Thanks in advance :)
EDIT:
This is the full Class:
/*
* 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);
// }
}
}
This is the 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
}
As i said before... I just get "empty" when i try:
System.out.println("INFO: " + ip + "\n" + db_name + "\n" + user + "\n" + password);
So JFrame
does not have a method or property called txt_jtextfield
Not knowing how you actually build this JFrame
it becomes difficult to know what to suggest.
Assuming you did something like...
JText txt_jtextfield = new JTextField();
JFrame obj = new JFrame();
// Some other initialisation code...
obj.add(txt_jtextfield);
You should be able to obtain the value directly.
If the field lives in it's "own" frame. You should be creating the parent frame directly
FrameWithTextFieldInIt obj = new FrameWithTextFieldInIt();
// etc...
Then it's up to the frame to provide access to the field (either by making it public, or, more preferably, by a getter)
You really need to provide more information about where the text field exists and in what context you are trying to access it
UPDATED
You can't use a JFrame
in this manner.
dbconfig_manager obj1 = new dbconfig_manager();
String ip = obj1.txt_ip.getText();
Is basically saying, "Make me a frame and continue running when you're done". Which means, there's nothing in the text fields.
Two options.
JDialog
instead, see How to make DialogsInstead of the db_connection_modifier
class been responsible for displaying the UI, make it only responsible for updating the properties and create the config frame with an "update" button of some kind that will call the db_connection_modifier
class
UPDATE
Max is also correct, in you're action handler for the "Guardar" button, you're doing this...
db_connection_modifier obj = new db_connection_modifier();
obj.hostconfig();
Which is creating a brand new dbconfig_manager
which has no details in it. You should be passing the properties to it directly...
db_connection_modifier obj = new db_connection_modifier(txt_ip.getText(), txt_db.getText(), txt_user.getText(), txt_pass.getText());
obj.hostconfig();
This will decouple your UI from your application logic