我正在用 java 做一个表单。
思路是:
当用户输入他的名字和第二个名字时,他必须按下“提交”按钮。现在我想通过提交按钮收听此操作,但我不知道如何获取用户在文本字段中输入的内容:“姓名”和“第二个姓名”。
我想通过提交按钮查看此数据,但我不知道是否可行。
或者我想知道当用户点击“提交”时我可以通过哪种方式看到所有这些数据。
谢谢,这是代码。
public class appNegozio extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
appNegozio frame = new appNegozio();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public appNegozio() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
SpringLayout sl_contentPane = new SpringLayout();
contentPane.setLayout(sl_contentPane);
textField = new JTextField();
sl_contentPane.putConstraint(SpringLayout.NORTH, textField, 10,
SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, textField, 62,
SpringLayout.WEST, contentPane);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
sl_contentPane.putConstraint(SpringLayout.NORTH, textField_1, 16,
SpringLayout.SOUTH, textField);
sl_contentPane.putConstraint(SpringLayout.WEST, textField_1, 0,
SpringLayout.WEST, textField);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblNome = new JLabel("Nome");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblNome, 10,
SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.EAST, lblNome, -7,
SpringLayout.WEST, textField);
contentPane.add(lblNome);
JLabel lblCognome = new JLabel("Cognome");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblCognome, 0,
SpringLayout.NORTH, textField_1);
sl_contentPane.putConstraint(SpringLayout.EAST, lblCognome, -6,
SpringLayout.WEST, textField_1);
contentPane.add(lblCognome);
JButton btnSubmit = new JButton("Submit");
sl_contentPane.putConstraint(SpringLayout.NORTH, btnSubmit, 24,
SpringLayout.SOUTH, textField_1);
sl_contentPane.putConstraint(SpringLayout.WEST, btnSubmit, 10,
SpringLayout.WEST, contentPane);
contentPane.add(btnSubmit);
}
}
最佳答案
一种简单的方法是为每个 JTextField
使用一个 final
局部变量。
您可以从添加到 JButton
的 ActionListener
中访问它们:
final JTextField textField = new JTextField();
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
System.out.println(textField.getText());
}
});
关于Java Swing : form with text fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444883/