从文本字段获取信息以在其他类的文本区域中使用它

时间:2011-07-27 02:21:59

标签: java swing user-interface jtextfield jtextarea

我有一个课程中有两个文本字段:“name”和“surname”。我需要有人输入的信息用于另一个类的文本区域。到目前为止,我设法写了(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 nameLabel = 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();
        }
    });
}
}

现在是另一个班级:

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();
        }
    });
}

}

但我在窗口中看到的是:“你今天好吗,null null?”有什么新鲜的眼睛能抓到什么问题?感谢

4 个答案:

答案 0 :(得分:3)

您从未向我们证明您已经证明在将文本输入字段之后以及在其他地方使用字符串变量之前调用了ActionListener。无论如何,这是一个糟糕的设计。

我将为该类提供JTextFields公共getter方法,而不是公共变量,并且在getter方法中,我将提取当前在相应JTextField中的文本。例如,像:

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

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

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

//... etc...

例如,这是一个SSCCE,它演示了您的问题和解决方案:

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());
            }
         }
      }));
   }
}

答案 1 :(得分:0)

更好地使用getter方法:

(人类):

// 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();}
// ...

另一堂课:

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);

答案 2 :(得分:0)

据我了解,当点击“enter”键时,只有JTextFields会触发动作(?)。请参阅此处的示例:Java Tutorial

如果您在文本字段中输入文本并在启动其他类/框架之前点击“输入”,它是否有效?

当然,更好的解决方案是吸气剂,如气垫船已经提到过:

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

答案 3 :(得分:-1)

一种方法是为值创建访问器。所以你应该:

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

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

在其他类中,您只需调用这些方法来返回值..

您应该将实例变量保留为私有,并且永远不要将它们公开(除非您有充分的理由)。请继续阅读Encapsulation