简体   繁体   English

通过选择JComboBox选项动态添加JTextField和JLabel

[英]Adding JTextFields and JLabels dynamically by selecting JComboBox option

I want to write a program that allows user to connect,view and add or delete values from database. 我想编写一个程序,允许用户连接,查看和添加或删除数据库中的值。 I'm stuck with the swing part. 我卡在秋千上了。 When i select a combobox option nothing happens but i want to create a view like mysql workbench. 当我选择一个组合框选项时,什么也没有发生,但是我想创建一个像mysql workbench这样的视图。 It suppose to be like that; 它应该是这样的; user picks a table name from combobox and can see column names from that table and textfields to add new values or existing values above column names. 用户从组合框中选择一个表名,并可以查看该表和文本字段中的列名,以在列名上方添加新值或现有值。

My code is this so far: 到目前为止,我的代码是:

public class DBC extends JFrame{

static String tablo;
static JTextField tf = new JTextField(20);
static int columnCount;
static JPanel tfPanel = new JPanel();
static JLabel depName = new JLabel("Name");
static JLabel depLocation = new JLabel("Location");
static Box box = new Box(BoxLayout.Y_AXIS);

public static void main(String[] args) throws Exception {

    Class.forName("com.mysql.jdbc.Driver");
    Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/project"
              ,"root","123456789");

    final Statement statement = connect.createStatement();

    JLabel tabloSec = new JLabel("Tablo Seçin:");
    final JComboBox<String> tablolar = new JComboBox<String>();
    DatabaseMetaData md = connect.getMetaData();
    final ResultSet rs = md.getTables(null, null, "%", null);
    while (rs.next()) {
        tablolar.addItem(rs.getString(3));
    }

    tablolar.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {

            tablo = tablolar.getSelectedItem().toString();

            try {
                 columnCount = rs.getMetaData().getColumnCount();
                 for(int i=0;i<=columnCount;i++ ){

                        box.add(tf);
                    }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    JButton ekle = new JButton("Ekle");
    ekle.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {

            try {
                switch(tablo){
                case "department":

                    statement.executeUpdate("INSERT INTO department(Name,Location) VALUES('"+tf.getText()+"')");
                case "employee":

                    statement.executeUpdate("INSERT INTO employee(Id,FirstName,LastName,Sex,Address,Email,Salary,BirthDate,JoinDate) VALUES('"+tf.getText()+"')");
                case "engineer":

                    statement.executeUpdate("INSERT INTO engineer(EngineerType) VALUES('"+tf.getText()+"')");
                case "manager":

                    statement.executeUpdate("INSERT INTO manager(Department) VALUES('"+tf.getText()+"')");
                case "project":

                    statement.executeUpdate("INSERT INTO project(Name,Number,Value) VALUES('"+tf.getText()+"')");
                case "secretary":

                    statement.executeUpdate("INSERT INTO secretary(TypingSpeed) VALUES('"+tf.getText()+"')");
                }

            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    JButton cik = new JButton("Çık");
    cik.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            System.exit(0);
        }
    });

    JPanel panel = new JPanel(new GridLayout(4,3));

    panel.add(tabloSec);
    panel.add(tablolar);
    panel.add(box);
    panel.revalidate();
    panel.add(ekle);
    panel.add(cik);

    JFrame frame = new JFrame("Deneme");
    frame.setSize(600,600);
    frame.setLocationRelativeTo(null);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

Looks like you're adding the same text field when iterating over the metadata of the result set: box.add(tf); 遍历结果集的元数据时,似乎要添加相同的文本字段: box.add(tf); . This will add the same text field only once. 这将只添加一次相同的文本字段。 You also need to validate() and repaint() the box container after adding new controls to it. 在向其添加新控件之后,还需要对box容器进行validate()repaint() Note that you also need to remove all controls from the box container when selecting new table. 请注意,选择新表时,还需要从box容器中删除所有控件。 You may need to introduce scroll pane. 您可能需要引入滚动窗格。 In addition, SQL statement execution refers to the same text field. 另外,SQL语句执行引用相同的文本字段。 Unless of course there is only one column and one value that is always should be updated. 当然,除非只有一列,并且始终应更新一个值。

All in all, unless this is a very specific solution for a very specific set of tables, you may consider using friendlier controls for this, perhaps a list or a table. 总而言之,除非这是针对一组非常特定的表的非常特定的解决方案,否则您可以考虑为此使用更友好的控件,也许是列表或表。 Maybe something similar to a properties table where first column specifies the name of the property, and the second column the value of that property. 也许类似于属性表,其中第一列指定属性的名称,第二列指定该属性的值。 The value column is editable. 值列是可编辑的。 You can repopulate the properties table once new SQL table is selected. 一旦选择了新的SQL表,就可以重新填充属性表。 Then on statement execution, just collect all the necessary values. 然后在执行语句时,只需收集所有必要的值即可。 As an alternative, you can also show the relevant view of a SQL table and let user tweak whatever values and then update SQL once done. 或者,您也可以显示SQL表的相关视图,并让用户调整任何值,然后在完成后更新SQL。 Look at Table From Database by @camickr. 查看@camickr的“ 数据库中的表”。

Also note that you should not execute SQL statements on Event Dispatch Thread , this may freeze your UI as long operations will block EDT. 还要注意,您不应该在Event Dispatch Thread上执行SQL语句,因为长时间的操作会阻塞EDT,这可能会冻结UI。 These operations should be handled on an auxiliary worker thread. 这些操作应在辅助工作线程上处理。 See Event Dispatch Thread . 请参阅事件调度线程 It is common to use SwingWorker to handle such lengthy tasks. 通常使用SwingWorker来处理这些冗长的任务。

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

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