Laura Cîrstea Laura Cîrstea -4 years ago 126
Java Question

Java return input text value on click event

How can I get the value of an input field when I click a button?

For example I need the value of

textName
input from the
PersonalInfo
class to be used in another class called
GenerateRDF


This is my code:

public class PersonalInfo extends JPanel {
private void initialize() {
....
JTextPane textName = new JTextPane();
textName.setBounds(95, 36, 302, 20);
panel.add(textName);

JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// send the value of `textName` to GenerateRDF
GenerateRDF generator = new GenerateRDF();
generator.setRDF();
}
});
}
}

public class GenerateRDF {
public void setRDF() {
String personURI = "http://localhost/amitkumar";
String fullName = textName;

// print here the value received from the `PersonalInfo` class
System.out.println(fullName);
Model model = ModelFactory.createDefaultModel();

Resource node = model.createResource(personURI)
.addProperty(VCARD.FN, fullName);
model.write(System.out);
}
}

Answer Source

You can do something like this:

public class PersonalInfo extends JPanel {
private void initialize() {
    ....
    JTextPane textName = new JTextPane();
    textName.setBounds(95, 36, 302, 20);
    panel.add(textName);

    JButton btnSave = new JButton("Save");
    btnSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            // send the value of `textName` to GenerateRDF
           GenerateRDF generator = new GenerateRDF();
           generator.setRDF(textName.getText());
        }
    }); 
  }
}

public class GenerateRDF {
  public void setRDF(String fullName) {
    String personURI    = "http://localhost/amitkumar";

    // print here the value received from the `PersonalInfo` class
    System.out.println(fullName);
    Model model = ModelFactory.createDefaultModel();

    Resource node = model.createResource(personURI)
             .addProperty(VCARD.FN, fullName);
    model.write(System.out);
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download