开发者

Getting information from a text field to use it in a text area in other Class

I've got one class that has two text fields in it: "name" and "surname". I need the information that someone typed in there for a text area in another class. So far I managed to write (Person class):

public class Person extends JPanel implements ActionListener {

TextField nameField;
JTextField surnameField;
public String name;
public String surname;
final static int BIG_BORDER = 75;
final static int SMALL_BORDER = 10;
final static int ELEMENTsLENGHT = 320;
final static int VERTICAL_SPACE = 10;
final static int VERTICAL_SPACE_PLUS = 25;
final static int HORIZONTAL_SPACE = 75;
final static int SPACEforELEMENT_LABEL = 50;
final static int SPACEforELEMENT_TEXT = 40;
final static int H_SPACEforBUTTON = 64;
final static int V_SPACEforBUTTON = 26; 

public Person() {
    init();
}

public void init() {

    JLabel name开发者_StackOverflow中文版Label = new JLabel("Please enter your name:");
    JLabel surnameLabel = new JLabel("Please enter your surname:");

    nameField = new JTextField();
    nameField.addActionListener(this);
    surnameField = new JTextField();
    surnameField.addActionListener(this);

    nextButton = new JButton("NEXT");
    nextButton.setActionCommand(next);
    nextButton.addActionListener(this);

    JPanel panelButton = new JPanel();
    panelButton.add(nextButton);        

    double size[][] = {
            { BIG_BORDER, ELEMENTsLENGHT, HORIZONTAL_SPACE,
                    H_SPACEforBUTTON, SMALL_BORDER }, // Columns
            { BIG_BORDER, SPACEforELEMENT_LABEL, VERTICAL_SPACE,
                    SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
                    SPACEforELEMENT_LABEL, VERTICAL_SPACE,
                    SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
                    SPACEforELEMENT_LABEL, VERTICAL_SPACE,
                    V_SPACEforBUTTON, SMALL_BORDER } }; // Rows

    setLayout(new TableLayout(size));

    add(nameLabel, "1,1,1,1");
    add(nameField, "1,3,1,1");
    add(surnameLabel, "1,5,1,1");
    add(surnameField, "1,7,1,1");
    add(nextButton, "3,11,1,1");
}   

public static void createAndShowGUI() {
    JFrame frame = new JFrame("Identification");
    frame.getContentPane().add(new Person());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(550, 450);
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {

    name = nameField.getText();
    surname = surnameField.getText();

    if (e.getActionCommand().equalsIgnoreCase(next)) {
        Person.showNextWindow();
    } 
}

public static void showNextWindow() {
    //cardLayout.next(this);
    System.out.println("go to the next window");
}

public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

The other class now:

public class Greeting extends JPanel implements ActionListener {

Person person = new Person();   

String name = person.name;
String surname = person.surname;

public Greeting() {
    super(new BorderLayout());
    init();
}

public void init() {

    nextButton = new JButton("NEXT");
    nextButton.setActionCommand(next);      
    nextButton.addActionListener(this);     
    //nextButton.setMnemonic('rightArrow');     

    String q = "How are you today, "+name+" "+surname+"?";          

    JTextArea textArea = new JTextArea(q); 
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setEditable(false);
    add(textArea, BorderLayout.NORTH);      

    JPanel btnPanel = new JPanel();     
    btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS));
    btnPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    btnPanel.add(Box.createHorizontalGlue());                       
    btnPanel.add(nextButton);
        btnPanel.setAlignmentX(RIGHT_ALIGNMENT);
    add(btnPanel, BorderLayout.SOUTH);      

} // end init

public static void showNextWindow() {
    //cardLayout.next(this);
    System.out.println("go to the next window");
}

public void actionPerformed(ActionEvent e) {

}

public static void createAndShowGUI() {

    JFrame frame = new JFrame("How are you");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new Greeting());     
    frame.setSize(550, 450);
    frame.setResizable(false);
    //frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

But what I see in the window is: "How are you today, null null?" Any fresh eyes to catch what's wrong? Thanks


You never show us that you've proven that the ActionListener's are called after the text has been entered into the fields and before the String variables are used elsewhere. Regardless, it's a bad design.

I'd give the class with the JTextFields public getter methods, not public variables, and in the getter methods, I'd extract the text currently in the corresponding JTextField. For instance, something like:

private JTextField nameField = new JTextField();
private JTextField surnameField = new JTextField();

public String getName() {
  return nameField.getText();
}

public String getSurname() {
  return surnameField.getText();
}

//... etc...

For example, here is an SSCCE that demonstrates your problem and a solution:

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

public class InfoFromTextFields {
   private static void createAndShowUI() {
      JFrame frame = new JFrame("InfoFromTextFields");
      frame.getContentPane().add(new MainGui());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

class NamePanel extends JPanel {
   private JTextField nameField = new JTextField(10);
   private JTextField surnameField = new JTextField(10);

   public NamePanel() {
      add(new JLabel("Name:"));
      add(nameField);
      add(Box.createHorizontalStrut(15));
      add(new JLabel("Surname:"));
      add(surnameField);
   }

   public String getNameText() {
      return nameField.getText();
   }

   public String getSurnameText() {
      return surnameField.getText();
   }
}

class MainGui extends JPanel {
   private JTextField nameField = new JTextField(10);
   private JTextField surnameField = new JTextField(10);

   public MainGui() {
      nameField.setEditable(false);
      surnameField.setEditable(false);

      add(new JLabel("Name:"));
      add(nameField);
      add(Box.createHorizontalStrut(15));
      add(new JLabel("Surname:"));
      add(surnameField);

      add(Box.createHorizontalStrut(15));
      add(new JButton(new AbstractAction("Get Names") {
         @Override
         public void actionPerformed(ActionEvent arg0) {
            NamePanel namePanel = new NamePanel();
            int result = JOptionPane.showConfirmDialog(nameField, namePanel,
                     "Get Names", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
               nameField.setText(namePanel.getNameText());
               surnameField.setText(namePanel.getSurnameText());
            }
         }
      }));
   }
}


As far as I understand it, action will be fired by JTextFields only (?) when the "enter" key is hit. See example here : Java Tutorial

Does it work if you enter text in the textfields AND hit "enter" before starting the other class/frame ?

Then of course a better solution is getters, like Hovercraft already mentioned :

public String getName(){
   return nameField.getText();
}


Better use getter methods:

(Person class):

// public String name;
// public String surname;
// ...

public Person()
{
    // ...
    nameField = new JTextField();
    nameField.addActionListener(this);
    surnameField = new JTextField();
    surnameField.addActionListener(this);

    // and in public void actionPerformed(ActionEvent e) {
    // name = nameField.getText();
    // surname = surnameField.getText();

    // ...
}
private String getName(){return nameField.getText();}
private String getSurname(){return surnameField.getText();}
// ...

The other class:

Person person = new Person();
String name = person.getName();
String surname = person.getSurname();

String q = "How are you today, "+name+" "+surname+"?";
JTextArea textArea = new JTextArea(q);


One way would be to create accessors for the values.. So you should have:

String getName()
{
     nameField.getText();
}

and

String getName()
{
     surnameField.getText();
} 

In you other class you just call those methods to return the values..

You should leave your instance variables as private and never make them public (unless you have a very good reason). Read on Encapsulation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜