简体   繁体   English

在运行时从创建的JTextfield获取值

[英]Get the value from created JTextfield at runtime

I've made an application that will get the column name of the database and create a jlabel and jtextfield at runtime based on the column names of the db. 我已经制作了一个应用程序,该应用程序将获取数据库的列名,并在运行时根据数据库的列名创建jlabel和jtextfield。

Here's the code snippet: Im using Netbeans here... 这是代码段:我在这里使用Netbeans ...

 public void getColumn(){
        String sql = "SELECT * from user";
        jPanel.setLayout(new GridLayout(0,2));

        try {
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();

            ArrayList<String> columns= new ArrayList<String>();
            for(int i = 1; i<= columnCount; i++){
                columns.add(rsmd.getColumnName(i));
                System.out.println(String.valueOf(columns));
            }
            ArrayList<JTextField> fields = new ArrayList<JTextField>();
        for(int i = 0; i <columns.size();i++){
                JLabel jl = new JLabel(String.valueOf(columns.get(i)));
            jPanel.add(jl);
            JTextField f = new JTextField(50);
            fields.add(f);
            jPanel.add(f);
                        this.revalidate();
                        this.repaint();
               }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }


This will be the sample output. 这将是示例输出。

id | ______________
fName | _____________
mName | _______________
lName | ________________

lines referring to JTextFields.. 引用JTextFields的行。

However, I can't get the values entered in the jtextfields. 但是,我无法获取在jtextfields中输入的值。 I've tried using the code below. 我尝试使用下面的代码。 But no luck. 但是没有运气。 Any help appreciated. 任何帮助表示赞赏。

for(JTextField field : fields){
                JOptionPane.showMessageDialog(null, field.getText());
        }

May be you can try this: 也许您可以尝试以下方法:

Component children[] = jp.getComponents();
for(Component child : children) {
  if(child instanceof JTextField) [
     JOptionPane.showMessageDialog(null, ((JTextField)child).getText());
  }
}

A better solution would be to use a JTable. 更好的解决方案是使用JTable。 Read the section from the Swing tutorial on How to Use Tables for more information. 阅读Swing教程中有关如何使用表的部分, 获取更多信息。

You can also check out Table From Database for some simple code to get you started. 您也可以从数据库中检出以获取一些简单的代码,以帮助您入门。 See the 'TableFromDatabaseExample' code for the easiest solution. 有关最简单的解决方案,请参见“ TableFromDatabaseExample”代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM