Laura Cîrstea
Laura Cîrstea

Reputation: 147

How to call a method from another class using Java

How can I call a method when I press a button from a separate class?

For example, when the click event fires on the Save button I want to call the setRDF method from the other class named GenerateRDF

This is my code:

public class PersonalInfo extends JPanel {
    private void initialize() {
        JButton btnSave = new JButton("Save");
        btnSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                // call the `setRDF` method here
            }
        }); 
   }
}

public class GenerateRDF extends Object {
      public void setRDF() {
        String personURI    = "http://localhost/amitkumar";
        String givenName    = "Amit";
        String familyName   = "Kumar";
        String fullName     = givenName+familyName;

        Model model = ModelFactory.createDefaultModel();

        Resource node = model.createResource(personURI)
                 .addProperty(VCARD.FN, fullName)
                 .addProperty(VCARD.N,
                              model.createResource()
                                   .addProperty(VCARD.Given, givenName)
                                   .addProperty(VCARD.Family, familyName));
        model.write(System.out);
    }
}

Upvotes: 1

Views: 87

Answers (1)

nhouser9
nhouser9

Reputation: 6780

You would create a new GenerateRDF object and call the method on that. For example:

public class PersonalInfo extends JPanel {
    private void initialize() {
        JButton btnSave = new JButton("Save");
        btnSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                GenerateRDF generator = new GenerateRDF();
                generator.setRDF();
            }
        }); 
   }
}

Side note: you don't need to write extends Ojbect; everything extends Object by default.

Upvotes: 1

Related Questions