How to Retrieve Value from Jtextfield in Java Swing

How to get the value of JTextField in Java Swing?

Your expectations involve magical thinking. Understand that insideTextField holds a String object, an object which in fact is immutable (cannot be changed). Yes, when you create the insideTextField you assign to it the String that just so happens to be residing within the JTextField, likely an empty "" String, but understand that when the JTextField's text properties change, the insideTextField will not, and in fact cannot magically change on its own. The solution is to not have a insideTextField field, and instead give the class a getter method that extracts the current String within the JTextField when it is needed. For example:

public String getUserName() {
return usernameField.getText();
}

Side note: I usually use a modal JDialog and not a JFrame to get log-in credentials. This way since the dialog is modal, I know when the user is done using it. And in fact a JOptionPane works as a quick and dirty modal dialog creator. For example if we had a login JPanel like so:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class LoginPanel extends JPanel {
private static final int GAP = 3;
private JTextField usernameField = new JTextField(10);
private JPasswordField passwordField = new JPasswordField(10);

public LoginPanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = getGbc(0, 0);
add(new JLabel("User Name:"), gbc);
gbc = getGbc(1, 0);
add(usernameField, gbc);
gbc = getGbc(0, 1);
add(new JLabel("Password:"), gbc);
gbc = getGbc(1, 1);
add(passwordField, gbc);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
}

private static GridBagConstraints getGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;

return gbc;
}

public String getUserName() {
return usernameField.getText();
}

public char[] getPassword() {
return passwordField.getPassword();
}
}

again one that uses getter methods to extract the text in the JTextField, we could display it in a JOptionPane like so:

JFrame frame = new JFrame("LoginExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// fill the JFrame with the main GUI
// ....

frame.pack();

// create the LoginPanel JPanel here
LoginPanel loginPanel = new LoginPanel();

// and display it in a JOptionPane here
int result = JOptionPane.showConfirmDialog(frame, loginPanel,
"User Log-In", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
String userName = loginPanel.getUserName();
char[] password = loginPanel.getPassword();

// test to make sure code is working
System.out.println("User Name: " + userName);

// check for name/password validity here
// ... if name/password OK, then show JFrame:
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

how to get value on TextField Java Swing

You shouldn't print the value before user clicks the button

public static void main(String[] args) {
HelloWorldSwing me = new HelloWorldSwing();
//me.print();//DON't PRINT HERE
}

Instead, you can do this in actionPerformed() method,

 loginBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
name = username_field.getText();
HelloWorldSwing.this.print();
}
});

This will print the value, you enter in your text field

How to retrieve value from JTextField in JTable?

1) How to retrive value from textfiled in JTable?

I assume you mean JTextField? Please be careful with your spelling since programming is an exercise in precision, and so you can't afford to be sloppy in your coding or your questions.

You get text just as the tutorials tell you, via the getText() method. Please have a look here.

2) After all the data how to store in database in one go?

Please clarify your question. If you're looking how to use databases with Java, look here. For how to use JTables and table models, please look here. I suggest that you separate out your database code from your Swing code, to help ease your debugging and coding.


Edit 1
Regarding using a JTable with a database, reams of answers have been posted on this question, and you would do well to search this site for these answers. It's not a trivial thing and will require a bit of study on your part. For example, please have a look at these links:

  • Most simple code to populate JTable from ResultSet
  • How to fill data in a JTable with database?
  • JTable Swing retrieve data
  • JDBC TableModel for a JTable in Java?

Edit 2
You ask in comment:

OK Let's stick one question.in above code I have create 2 JTexfield and and Button.Now here I want those retrieved data how can I show in Jtable?

If you want the data from the two JTextFields placed in a row of the JTable, consider doing the following:

  • In your button's ActionListener, first extract the text from the text from the JTextFields.
  • Next you will need to create a row for your JTable which means adding a row to the JTable's model. How this is done will depend entirely on how the TableModel is set up.
  • If you are using a DefaultTableModel object, then you'll want to create a Vector<String> or String array, place your two Strings into the Vector or array, and then call addRow(rowData) on your DefaultTableModel variable. This assumes that the vector or array is named rowData.
  • If you're using a custom TableModel based off of the AbstractTableModel, then you'll need to write your own addRow(...) method, and you will likely pass in an object of a custom class that holds your two pieces of data. If you go this route, make sure that your addRow(...) method calls the correct fireTableXXX(...) method, here it will be fireTableRowsInserted(int firstRow, int lastRow).

But most important, please be sure to read the JTable tutorial that I've linked to above, else my answers will not make sense to you.


Edit 3
For example, using a DefaultTableModel:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class MyTableEg extends JPanel {
private static final String[] COLUMNS = {"Column A", "Column B"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0);
private JTable table = new JTable(model);
private JTextField fieldA = new JTextField(10);
private JTextField fieldB = new JTextField(10);
private JButton button = new JButton(new ButtonAction("Add Data", KeyEvent.VK_A));

public MyTableEg() {
JPanel topPanel = new JPanel();
topPanel.add(fieldA);
topPanel.add(fieldB);
topPanel.add(button);

setLayout(new BorderLayout());
add(topPanel, BorderLayout.NORTH);
add(new JScrollPane(table), BorderLayout.CENTER);
}

private class ButtonAction extends AbstractAction {
public ButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent evt) {

// ***** here's the important bit of code

Vector<String> rowData = new Vector<String>(); // create a row Vector
rowData.add(fieldA.getText()); // fill it with data from JTextFields
rowData.add(fieldB.getText());
model.addRow(rowData); // and add to table model
}
}

private static void createAndShowGui() {
JFrame frame = new JFrame("MyTableEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyTableEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Retrieve JTextField text value

((JTextComponent) x[i]).getText(); should work.

(Just because x[i] is an instance of a JTextComponent, doesn't mean it's neccesarily a JTextField though.) But JTextComponent has a .getText() so casting to JTextComponent should be ok.

How to get TextField value from another class or method

You can declare your JTextField globally and then you initialize it inside your constructor. Now you have access to your variable in your methods too.

public class MyGUI extends JPanel
{
private JTextField betText;

public MyGUI(){
//other operations
betText = new JTextField("");
}

public void test(){
String a = betText.getText();
}
}


Related Topics



Leave a reply



Submit