Get value from JtextField to another class [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im trying to get jTextField value in another class but always get error null exception. Here is my code :
Class Main :
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility();
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
Class another:
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}
What's wrong in this code ?

You should create instance of FormTambahDoc before you ca use it:
FormTambahDoc formTambahDoc = new FormTambahDoc(); or get the instance from somewhere. Otherwise formTambahDoc will always be null. Check again your AWT tutorial.

Try following
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility(this);
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public Utility(FormTambahDoc aForm) {
formTambahDoc = aForm;
}
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}

Related

Name for pattern that allows only certain classes to construct another class

I have to write a test for the login dialog that shows up on my website, but there are two, and only two access points for this login dialog. Ideally, my page objects should reflect the restricted access to this login dialog.
When you clickLogin on the Header, a LoginDialog pops up
When you postComment on an Article, and you aren't logged in (and we'll assume you aren't for simplicity), a LoginDialog pops up.
Here's what it looks like in code:
new LoginDialog().login(); // shouldn't be allowed
new Header().clickLogin().login(); // should be allowed
new Article().postComment().login() // should be allowed
I came up with a method for getting around this. LoginDialog only has two constructors, which both take in an object that can only be constructed in either Header or Article.
public class LoginDialogTest extends WebTest {
#Test
public void testLoginDialogFromHeader {
new HomePage().loadPage();
new Header().clickLogin().login();
verifyLoggedIn();
}
#Test
public void testLoginDialogFromArticleComment {
new ArticlePage(42).loadPage(); // Load an article with id=42
new Article().postComment().login();
verifyLoggedIn();
}
}
public class LoginDialog {
public LoginDialog(Article.CommentButton commentButton) {
}
public LoginDialog(Header.LoginButton loginButton) {
}
public void login() {
}
}
public class Article {
public class CommentButton {
private CommentButton() {
}
public LoginDialog click() {
return new LoginDialog(this);
}
}
public LoginDialog postComment() {
return new CommentButton().click();
}
}
public class Header {
public class LoginButton {
public LoginDialog click() {
return new LoginDialog(this);
}
}
public LoginDialog clickLogin() {
return new LoginButton().click();
}
}
My question is whether or not this is an existing pattern, and if it is, what is its name? If it isn't, what would be a good name for it?
I think this would be a foolproof way of making sure only Header or Article could create a LoginDialog:
public class LoginDialog {
private LoginDialog() {
... code to construct
}
public interface Constructor {
LoginDialog newLoginDialog();
}
private static class ConstructorImpl implements Constructor {
public LoginDialog newLoginDialog() {
return new LoginDialog();
}
}
private static ConstructorImpl constructor;
static {
constructor = new ConstructorImpl();
Header.provideLoginDialogConstructor(constructor);
Article.provideLoginDialogConstructor(constructor);
}
}
and in Header and Article, provide a public provideLoginDialogConstructor method:
private static LoginDialog.Constructor constructor;
public static void provideLoginDialogConstructor(LoginDialog.Constructor constructor) {
Header.constructor = constructor; // or Article.constructor
}
and when those classes need to construct a LoginDialog:
if (!loggedIn()) {
return constructor.newLoginDialog();
} else {
return null;
}
Since the LoginDialog class decides what classes get to have its private object to construct a LoginDialog, there should be no way for another class to obtain the ability to construct one using normal means [there might be tricky ways using reflection].
Note: I haven't tested this.

Java - force implementation of a method for each child of an abstract class

I have an abstract class Action with children like SendMessageAction.
I would like to run these actions in a service but how could I force implementation of each child ?
For example I would like to implement an abstract method : void run(Action action)
and methods "run" for each possible Action with an error if some methods are missing.
Any idea ?
Something like below should help you to get started. Happy coding!
Action.java
public abstract class Action {
protected abstract void runAction();
}
MessageSenderAction.java
public class MessageSenderAction extends Action {
public void runAction() {
//send message
}
}
SomeOtherAction.java
public class SomeOtherAction extends Action {
public void runAction() {
//do something else
}
}
ActionHandler.java
public class ActionHandler {
private final static ActionHandler INSTANCE = new ActionHandler();
private ActionHandler() {}
public static ActionHandler getInstance() {
return INSTANCE;
}
private List<Action> allActions = new ArrayList<Action>();
public void addAction(Action action) {
allActions.add(action);
}
public void runAllActions() {
for(Action action: allActions) {
//just to handle exception if there is any. Not to hamper other actions in case of any failures
try {
action.runAction();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
ActionDemo.java
public class ActionDemo {
public static void main(String... args) {
ActionHandler actionHandler = ActionHandler.getInstance();
Action msgSenderAction = new MessageSenderAction();
Action someOtherAction = new SomeOtherAction();
actionHandler.addAction(msgSenderAction);
actionHandler.addAction(someOtherAction);
actionHandler.runAllActions();
}
}

Java inner class access outer class variable

I have a question about inner class access. I am not experienced in Java, so please bear with me.
Below is the code i wrote:
public class MainFrame extends JFrame {
...
private String selectedNodeString = NULL; //outer class variable
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
class MyTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
selectedNodeString = //compile error, can not resolve type
}
}
}
Below is an example from "thinking in java" explaining inner class access, where inner class can access outer class variable.
interface Selector {
...
}
public class Sequence {
private Object[] items;
private class SequenceSelector implements Selector {
...
private int i = 0;
public boolean end() { return i == items.length; }
public Object current() { return items[i]; }
public void next() { if(i < items.length) i++; }
}
}
So what is wrong with my code, is it more than 1 layer of inner class, and how to fix it?
Thanks
You are missing a curly brace after the method createControlpanel.
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
} // missing this one.

How to call the run method from another class?

Sorry, if this is a stupid question.
I would like to find out how to call the run method that is located in
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
from the class AdaugaComanda.java.
The run method is declared in FereastraPrincipala.java and I want to call this from AdaugaComanda.java, so that changes can be seen to FereastraPrincipala after introducing values in the textfields from AdaugaChitanta.java. If I don't call a method, then I have to run FereastraPrincipala.java again, in order to see the new info in the JTabbedPane.
Here is the code for FereastraPrincipala.java
package sakila.ui;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import sakila.entity.*;
import sakila.util.HibernateUtil;
public class FereastraPrincipala extends javax.swing.JFrame {
public FereastraPrincipala() {
initComponents();
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AdaugaComanda ac = new AdaugaComanda();
ac.setVisible(true);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FereastraPrincipala().setVisible(true);
Session session = HibernateUtil.getSessionFactory().openSession();
try{
List<Comanda> comenzi = session.createQuery("from Comanda").list();
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("IdComanda");
tableHeaders.add("Depozit");
tableHeaders.add("Furnizor");
tableHeaders.add("Client");
tableHeaders.add("Produs");
tableHeaders.add("Cantitate");
tableHeaders.add("Unit de mas");
for (Comanda comanda : comenzi) {
Vector <Object> oneRow = new Vector <Object>();
oneRow.add(comanda.getIdcomanda());
oneRow.add(comanda.getDepozit() == null ? "" : comanda.getDepozit().toString());
oneRow.add(comanda.getFurnizor() == null ? "" : comanda.getFurnizor().toString());
oneRow.add(comanda.getClient() == null ? "" : comanda.getClient().toString());
oneRow.add(comanda.getProdus() == null ? "" : comanda.getProdus().toString());
oneRow.add(comanda.getCantitate());
oneRow.add(comanda.getUnitmas());
tableData.add(oneRow);
}
ComandaTable.setModel(new DefaultTableModel(tableData, tableHeaders));
}catch (Exception he){
he.printStackTrace();
}
}
});
}
}
Here is the code for AdaugaComanda.java
package sakila.ui;
import java.io.EOFException;
import java.util.List;
import sakila.entity.*;
import sakila.service.Functie;
import sakila.entity.Client;
public class AdaugaComanda extends javax.swing.JDialog {
public AdaugaComanda() {
initComponents();
initComboBoxes();
}
private void initComboBoxes() {
DepozitComboBox.removeAllItems();
FurnizorComboBox.removeAllItems();
ClientComboBox.removeAllItems();
ProdusComboBox.removeAllItems();
System.out.println("sterge itemurile");
List<Depozit> depozite = (List<Depozit>) sakila.client.Client.citeste(Functie.LISTEAZA_DEPOZITE);
for (Depozit depozit : depozite)
DepozitComboBox.addItem(depozit);
List<Furnizor> furnizori = (List<Furnizor>) sakila.client.Client.citeste(Functie.LISTEAZA_FURNIZORI);
for (Furnizor furnizor : furnizori)
FurnizorComboBox.addItem(furnizor);
List<Client> clienti = (List<Client>) sakila.client.Client.citeste(Functie.LISTEAZA_CLIENTI);
for (Client client : clienti)
ClientComboBox.addItem(client);
List<Produs> produse = (List<Produs>) sakila.client.Client.citeste(Functie.LISTEAZA_PRODUSE);
for (Produs produs : produse)
ProdusComboBox.addItem(produs);
System.out.println("adaugaitemuri");
}
private void ClientComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void InsereazaButtonActionPerformed(java.awt.event.ActionEvent evt) {
runQueryBasedOnInsert();
}
private void runQueryBasedOnInsert(){
Comanda comanda = new Comanda();
Depozit depozit = (Depozit)DepozitComboBox.getSelectedItem();
comanda.setDepozit(depozit);
Furnizor furnizor = ((Furnizor)FurnizorComboBox.getSelectedItem());
comanda.setFurnizor(furnizor);
sakila.entity.Client client = ((sakila.entity.Client)ClientComboBox.getSelectedItem());
comanda.setClient(client);
Produs produs = ((Produs)ProdusComboBox.getSelectedItem());
comanda.setProdus(produs);
comanda.setCantitate(Integer.parseInt(CantitateTextField.getText()));
comanda.setUnitmas(UnitMasTextField.getText());
sakila.client.Client.scrie(Functie.CREAZA_COMANDA, comanda);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdaugaComanda().setVisible(true);
}
});
}
Maybe someone could help me. Thank you a lot!
You could make FereastraPrincipala a member variable of AnduagaChitanta.
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala = new FereastraPrincipala (); //Or inject it into the constructor
private void SomeMethod()
{
fPrincipala.run();
}
}
in the run method()
public void run()
{
setvisible(true);
}
If you are wondering how to inject it:
public class AnduagaChitanta
{
FereastraPrincipala fPrincipala
public AnduagaChitanta(FereastraPrincipala fPrinicipala)
{
this.fPrinicipala = fPrinicipala;
}
private void SomeMethod()
{
fPrincipala.run();
}
}
If you like you can make FereastraPrincipala implement an interface so the definition of the constructor can be:
public AnduagaChitanta(ISomethingPrinicipala fPrinicipala)
But now we are going into design patterns so I will leave it at that.
Update
After your update I would do something like this:
FereastraPrincipala extends JFrame implements Runnable
{
public void run()
{
setvisible(true) ;
}
}
I don't know where but maybe in your AnduagaChitanta class I would do this
public void SomeMethod()
{
java.awt.EventQueue.invokeLater(fPrinicpala)
}
I hope that makes sense
Never call run() method of thread. It executes in the current thread it self !! Always call start() method. Coming to your case, create a new class so that you could invoke start() on it from other places

Access variable in actionPerformed

I have a class SaveFile implementing ActionListener. The method in it takes a string argument compleName. How do I make completeName be accessable in actionPerformed method in that class.
Thanks
class SaveFile implements ActionListener {
public void uploadToDatabase(String completeName){
}
public void actionPerformed(ActionEvent e) {
// I want to access completeName here
}
}
}
just use it as a variable inside your class
class SaveFile implements ActionListener {
private string completeName;
public void uploadToDatabase(String compName){
//code...
this.completeName = compName;
}
public void actionPerformed(ActionEvent e) {
System.out.println(completeName);
}
}
}
Simply ensure you store completeName as an instance variable.
class SaveFile implements ActionListener {
private String completeName;
public void uploadToDatabase(String completeName){
// do other things
this.completeName = completeName;
}
public void actionPerformed(ActionEvent e) {
// use this.completeName to get that value
}
}
}

Categories