1

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!

//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Customer extends JFrame {
    Function fun = new Function();

    public static void main(String[]args){
        Customer.setLookAndFeel();
        Customer cust = new Customer();
    }


    public Customer(){
        super("Resident Details");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        FlowLayout two = new FlowLayout(FlowLayout.LEFT);
        setLayout(two);


        JPanel row1 = new JPanel();
        JLabel name = new JLabel("First Name",JLabel.LEFT);
        JTextField nameEntry = new JTextField("",20);
        row1.add(name);
        row1.add(nameEntry);
        add(row1);

        JPanel row2 = new JPanel();
        JLabel surname = new JLabel("Surname    ",JLabel.LEFT);
        JTextField surnameEntry = new JTextField("",20);
        row2.add(surname);
        row2.add(surnameEntry);
        add(row2);

        JPanel row3 = new JPanel();
        JLabel contact1 = new JLabel("Contact Details : Email                 ",JLabel.LEFT);
        JTextField contact1Entry = new JTextField("",10);
        FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
        setLayout(newflow);
        row3.add(contact1);
        row3.add(contact1Entry);
        add(row3);

        JPanel row4 = new JPanel();
        JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
        JTextField contact2Entry = new JTextField("",10);
        row4.add(contact2);
        row4.add(contact2Entry);
        add(row4);

        JPanel row5 = new JPanel();
        JLabel time = new JLabel("Duration Of Stay                             ",JLabel.LEFT);
        JTextField timeEntry = new JTextField("",10);
        row5.add(time);
        row5.add(timeEntry);
        add(row5);


        JPanel row6 = new JPanel();
        JComboBox<String> type = new JComboBox<String>();
        type.addItem("Type Of Room");
        type.addItem("Single Room");
        type.addItem("Double Room");
        type.addItem("VIP Room");
        row6.add(type);
        add(row6);

        JPanel row7 = new JPanel();
        FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(amt);
        JLabel amount = new JLabel("Amount Per Day                               ");
        JTextField AmountField = new JTextField("\u20ac ",10);
        row7.add(amount);
        row7.add(AmountField);
        add(row7);

        JPanel row8 = new JPanel();
        FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
        setLayout(prc);
        JLabel price = new JLabel("Total Price                                         ");
        JTextField priceField = new JTextField("\u20ac ",10);
        row8.add(price);
        row8.add(priceField);
        add(row8);

        JPanel row9 = new JPanel();
        JButton clear = new JButton("Clear");
        row9.add(clear);
        add(row9);

        JPanel row10 = new JPanel();
        JButton save = new JButton("Save");
        save.addActionListener(fun);
        row10.add(save);
        add(row10);

        //Adding ActionListners
        nameEntry.addActionListener(fun);
        clear.addActionListener(fun);
        save.addActionListener(fun);

        setVisible(true);
    }

    private static void setLookAndFeel() {
            try {
                UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
                );
            } catch (Exception exc) {
            // ignore error
                }
    }

}

//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;


//Class Name
public class Function implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if(command.equals("Add Customer")) {
            Login();
        }
        else if(command.equals("Register")){
            Registration();
        }
        else if(command.equals("Exit")){
            System.exit(0);
        }       
        else if(command.equals("Clear")){
            ClearAllFields();
        }
        else if(command.equals("Save")){
            SaveIt();
        }
    }

    public static void Login(){
        Customer cust = new Customer();
    }

    public static void Registration(){
        //Do Nothing

    }
    //This clears all the text from the JTextFields
    public static void ClearAllFields(){

    }

    //This will save Info on to another Class
    public static void SaveIt(){


    }


}
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
Java_Man
  • 13
  • 3
  • 1
    Please elaborate on what you mean by `"but it won't work". How is it not working? Does it compile? Run? Does it throw an exception? Please give us any and all information that would help us to better understand your code and your question. – Hovercraft Full Of Eels Aug 13 '17 at 15:36
  • Please look into creating a [mcve]. Also, can you include the clearAll method and what class you are calling it from? – Luke Thistlethwaite Aug 13 '17 at 15:38
  • it wont compile,it gives an error saying "cannot find symbol name.Entry" – Java_Man Aug 13 '17 at 15:39
  • You're overusing static modifiers in your second class. Give the GUI a public `clearAll()` method, pass the GUI instance into the 2nd class, and have it call that method. – Hovercraft Full Of Eels Aug 13 '17 at 15:42
  • the clearAll method takes the user input from nameEntry JTextfield and set it to clear using function class – Java_Man Aug 13 '17 at 15:42
  • Your question is basically, how can one object call methods on another. The answer is simple: pass in references and call the appropriate methods. That's it. Better would be to use a Model-View-Controller code structure, but that would be over-kill at this point. – Hovercraft Full Of Eels Aug 13 '17 at 15:43
  • I tried that now i have an exception " Exception in thread AWT -event queue-0" "java.lang.NullPointerException at Function actionperformed" – Java_Man Aug 13 '17 at 16:47
  • Then please check out the decent answers to be found in [this similar question](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Hovercraft Full Of Eels Aug 13 '17 at 16:49

2 Answers2

1

Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class GUI extends JPanel {
    private JTextField textField = new JTextField(10);
    private JButton clearButton = new JButton("Clear");

    public GUI() {
        // pass **this** into the listener class
        MyListener myListener = new MyListener(this);
        clearButton.addActionListener(myListener);
        clearButton.setMnemonic(KeyEvent.VK_C);

        add(textField);
        add(clearButton);
    }

    // public method in GUI that will do the dirty work
    public void clearAll() {
        textField.setText("");
    }

    // other public methods here to get text from the JTextFields
    // to set text, and do whatever else needs to be done

    private static void createAndShowGui() {
        GUI mainPanel = new GUI();

        JFrame frame = new JFrame("GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MyListener implements ActionListener {
    private GUI gui;

    // use constructor parameter to set a field
    public MyListener(GUI gui) {
        this.gui = gui;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        gui.clearAll();  // call public method in field
    }
}

A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
1

Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:

JTextField nameEntry = new JTextField("",20);

Function fun = new Function(nameEntry);

Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:

JTextField nameEntry;

public Function(JTextField nameEntry) {
    this.nameEntry = nameEntry;
}

Now, the following will compile:

public void ClearAllFields(){
    nameEntry.setText("");
}

And, the Clear button will clear the name field.

Charles
  • 196
  • 7
  • thanks Charles it finally works I appreciate the help, Hovercraft Full Of Eels thank you for your help too – Java_Man Aug 14 '17 at 21:29