使用Java Swings和mysql自动填充表单

时间:2013-11-06 04:45:25

标签: java mysql swing jtable jtextfield

我在我的这个小项目中使用java swing。我有四个文本字段rollno,名称,类和部分以及搜索按钮。一旦我点击搜索按钮(文本字段为空)我得到一个列表新表中数据库中所有表项(与文本字段相同的列名)(使用Jtable)。这就是我目前所拥有的。

现在假设我点击了一行,我希望用鼠标点击这些数据出现在文本字段中,我应该怎么做?

这是我的代码:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.sql.*;
import java.awt.event.*;

public class SearchResult implements ActionListener{
    JFrame frame,frame1;
    JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
    JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
    JButton button;
    JPanel panel;
    static JTable table;

    String driverName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/mydb";
    String userName = "root";
    String password = "root";
    String[] columnNames = {"Roll No", "Name", "Class", "Section"};

    public void createUI()
    {
        frame = new JFrame("Database Search Result");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        textbox = new JTextField();
        textbox.setBounds(120,30,150,20); 
        label=new JLabel("Roll No.");
        label.setBounds(10, 30, 100, 20);
        textbox1 = new JTextField();
        textbox1.setBounds(120,50,150,20); 
        label1=new JLabel("Name");
        label1.setBounds(10, 50, 100, 20);
        textbox2 = new JTextField();
        textbox2.setBounds(120,70,150,20); 
        label2=new JLabel("Class");
        label2.setBounds(10, 70, 100, 20);
        textbox3 = new JTextField();
        textbox3.setBounds(120,90,150,20); 
        label3=new JLabel("Section");
        label3.setBounds(10, 90, 100, 20);
        button = new JButton("search");
        button.setBounds(120,230,150,20);
        button.addActionListener(this);
        frame.add(textbox);
        frame.add(label);
        frame.add(textbox1);
        frame.add(label1);
        frame.add(textbox2);
        frame.add(label2);
        frame.add(textbox3);
        frame.add(label3);
        frame.add(button);
        frame.setVisible(true);
        frame.setSize(500, 400);        
    }   

    public void actionPerformed(ActionEvent ae)
    {
        button = (JButton)ae.getSource();
        System.out.println("Showing Table Data.......");
            showTableData();            
    }   

    public void showTableData()
    {

        frame1 = new JFrame("Database Search Result");
        //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());       
        //TableModel tm = new TableModel();
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);
        //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());      
        //table = new JTable(model);
        table = new JTable();
        table.setModel(model);      
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);      
        String textvalue = textbox.getText();
        String roll= "";
        String name= "";
        String cl = "";
        String sec = "";
        try
        {           
            Class.forName(driverName);      
            Connection con = DriverManager.getConnection(url, userName, password);
            //String sql = "select * from student where rollno = "+textvalue;
            String sql="select * from student";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            int i =0;
            while(rs.next())
            {
                roll = rs.getString("rollno");
                name = rs.getString("name");
                cl = rs.getString("class");
                sec = rs.getString("section");                  
                model.addRow(new Object[]{roll, name, cl, sec});

            }
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(400,300);
    }

    public static void main(String args[])
    {
        SearchResult sr = new SearchResult();
                sr.createUI();              
    }
}

更新代码

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.sql.*;
import java.util.Vector;
import java.awt.event.*;

public class barcoder implements ActionListener{
    JFrame frame,frame1;
    JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
    JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
    JButton button;
    JPanel panel;
    static JTable table;

    String driverName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/mydb";
    String userName = "root";
    String password = "root";
    String[] columnNames = {"Roll No", "Name", "Class", "Section"};

    public void createUI()
    {
        frame = new JFrame("Database Search Result");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        textbox = new JTextField();
        textbox.setBounds(120,30,150,20); 
        label=new JLabel("Roll No.");
        label.setBounds(10, 30, 100, 20);
        textbox1 = new JTextField();
        textbox1.setBounds(120,50,150,20); 
        label1=new JLabel("Name");
        label1.setBounds(10, 50, 100, 20);
        textbox2 = new JTextField();
        textbox2.setBounds(120,70,150,20); 
        label2=new JLabel("Class");
        label2.setBounds(10, 70, 100, 20);
        textbox3 = new JTextField();
        textbox3.setBounds(120,90,150,20); 
        label3=new JLabel("Section");
        label3.setBounds(10, 90, 100, 20);
        button = new JButton("search");
        button.setBounds(120,230,150,20);
        button.addActionListener(this);
        frame.add(textbox);
        frame.add(label);
        frame.add(textbox1);
        frame.add(label1);
        frame.add(textbox2);
        frame.add(label2);
        frame.add(textbox3);
        frame.add(label3);
        frame.add(button);
        frame.setVisible(true);
        frame.setSize(500, 400);        
    }   

    public void actionPerformed(ActionEvent ae)
    {
        button = (JButton)ae.getSource();
        System.out.println("Showing Table Data.......");
            showTableData();            
    }   

    public void showTableData()
    {

        frame1 = new JFrame("Database Search Result");
        //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());       
        //TableModel tm = new TableModel();
         DefaultTableModel model = new DefaultTableModel(){
            @Override
            public boolean isCellEditable(int row, int column) { 
             return false;  
            }
        };
        model.setColumnIdentifiers(columnNames);
        //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());      
        //table = new JTable(model);
        table = new JTable();
        table.setModel(model); 
        model.addTableModelListener(new TableModelListener() {
            int row = table.getSelectedRow();
            @Override
            public void tableChanged(TableModelEvent arg0) {
                int row = table.getSelectedRow();
                System.out.println("Selecte table row = " + row);
                if (row != -1) {
                    int modelRow = table.convertRowIndexToModel(row);
                    System.out.println("Selecte model row = " + row);
                    Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
                    textbox.setText(data.get(0).toString());
                    textbox1.setText(data.get(1).toString());
                    textbox2.setText(data.get(2).toString());
                    textbox3.setText(data.get(3).toString());
                }
            }
        });
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
                    if (table.getSelectedRow() != -1) {
                        SwingUtilities.getWindowAncestor(table).dispose();
                    }
                }
            }
        });
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);      
        String textvalue = textbox.getText();
        String roll= "";
        String name= "";
        String cl = "";
        String sec = "";
        try
        {           
             Class.forName(driverName);      
            Connection con = DriverManager.getConnection(url, userName, password);
            //String sql = "select * from student where rollno = "+textvalue;
            String sql="select * from student";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            int i =0;
            while(rs.next())
            {
                roll = rs.getString("rollno");
                name = rs.getString("name");
                cl = rs.getString("class");
                sec = rs.getString("section");                  
                model.addRow(new Object[]{roll, name, cl, sec});

            }
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(400,300);
    }

    public static void main(String args[])
    {
        barcoder sr = new barcoder();
                sr.createUI();              
    }
}

2 个答案:

答案 0 :(得分:2)

例如,鼠标,键盘或编程方式可能会出于多种原因而发生选择更改。

您最好的选择可能是在表格选择模型中添加ListSelectionListener并在那里进行更改。例如......

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
        int row = table.getSelectedRow();
        if (row != -1) {
            int modelRow = table.convertRowIndexToModel(row);
            Vector data = (Vector)((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
        }
    }
});

当选择更改时,将获取指定行的列数据...

查看提供其他示例的How to use tables

更新了工作示例

因为我无法访问您的数据库,所以我将这个简单的示例放在一起,演示了基本的想法

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

public class TestTable {

    public static void main(String[] args) {
        new TestTable();
    }

    public TestTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                DefaultTableModel model = new DefaultTableModel();

                final JTextField rollField = new JTextField(10);
                final JTextField nameField = new JTextField(10);
                final JTextField classField = new JTextField(10);
                final JTextField sectionField = new JTextField(10);

                JPanel details = new JPanel(new GridLayout(1, 4));
                details.add(rollField);
                details.add(nameField);
                details.add(classField);
                details.add(sectionField);

                model.setColumnIdentifiers(new String[]{"Roll No", "Name", "Class", "Section"});
                model.addRow(new String[]{"1", "Happy", "Warrior", "Inner"});
                model.addRow(new String[]{"2", "Sad", "Mage", "Outter"});
                model.addRow(new String[]{"3", "Jug Head", "Clown", "Outter space"});

                final JTable table = new JTable(model);
                table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                    @Override
                    public void valueChanged(ListSelectionEvent e) {
                        int row = table.getSelectedRow();
                        System.out.println("Selecte table row = " + row);
                        if (row != -1) {
                            int modelRow = table.convertRowIndexToModel(row);
                            System.out.println("Selecte model row = " + row);
                            Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
                            rollField.setText(data.get(0).toString());
                            nameField.setText(data.get(1).toString());
                            classField.setText(data.get(2).toString());
                            sectionField.setText(data.get(3).toString());
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(details, BorderLayout.NORTH);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

更新了示例覆盖isCellEditable

DefaultTableModel model = new DefaultTableModel() {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }                    
};

更新了双击表格时关闭窗口的示例

table.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
            if (table.getSelectedRow() != -1) {
                SwingUtilities.getWindowAncestor(table).dispose();
            }
        }
    }
});

答案 1 :(得分:0)

遵循这种方法,

单击表格中的行,读取所选行的值并将其填入相应的字段中。

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.sql.*;
import java.awt.event.*;

public class SearchResult implements ActionListener{
    JFrame frame,frame1;
    JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
    JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
    JButton button;
    JPanel panel;
    static JTable table;

    String driverName = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/mydb";
    String userName = "root";
    String password = "root";
    String[] columnNames = {"Roll No", "Name", "Class", "Section"};

    public void createUI()
    {
        frame = new JFrame("Database Search Result");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        textbox = new JTextField();
        textbox.setBounds(120,30,150,20); 
        label=new JLabel("Roll No.");
        label.setBounds(10, 30, 100, 20);
        textbox1 = new JTextField();
        textbox1.setBounds(120,50,150,20); 
        label1=new JLabel("Name");
        label1.setBounds(10, 50, 100, 20);
        textbox2 = new JTextField();
        textbox2.setBounds(120,70,150,20); 
        label2=new JLabel("Class");
        label2.setBounds(10, 70, 100, 20);
        textbox3 = new JTextField();
        textbox3.setBounds(120,90,150,20); 
        label3=new JLabel("Section");
        label3.setBounds(10, 90, 100, 20);
        button = new JButton("search");
        button.setBounds(120,230,150,20);
        button.addActionListener(this);
        frame.add(textbox);
        frame.add(label);
        frame.add(textbox1);
        frame.add(label1);
        frame.add(textbox2);
        frame.add(label2);
        frame.add(textbox3);
        frame.add(label3);
        frame.add(button);
        frame.setVisible(true);
        frame.setSize(500, 400);        
    }   

    public void actionPerformed(ActionEvent ae)
    {
        button = (JButton)ae.getSource();
        System.out.println("Showing Table Data.......");
            showTableData();            
    }   

    public void showTableData()
    {

        frame1 = new JFrame("Database Search Result");
        //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());       
        //TableModel tm = new TableModel();
        final DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);
        //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());      
        //table = new JTable(model);
        table = new JTable();
        table.setModel(model); 
        model.addTableModelListener(new TableModelListener() {
            int row = table.getSelectedRow();
            @Override
            public void tableChanged(TableModelEvent arg0) {
                int modelRow = table.convertRowIndexToModel(row);

                textbox1.setText(model.getDataVector().get(0).toString());


            }
        });
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);      
        String textvalue = textbox.getText();
        String roll= "";
        String name= "";
        String cl = "";
        String sec = "";
        try
        {           
             Class.forName(driverName);      
            Connection con = DriverManager.getConnection(url, userName, password);
            //String sql = "select * from student where rollno = "+textvalue;
            String sql="select * from student";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            int i =0;
            while(rs.next())
            {
                roll = rs.getString("rollno");
                name = rs.getString("name");
                cl = rs.getString("class");
                sec = rs.getString("section");                  
                model.addRow(new Object[]{roll, name, cl, sec});

            }
        }
        catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(400,300);
    }

    public static void main(String args[])
    {
        SearchResult sr = new SearchResult();
                sr.createUI();              
    }
}