JTables和MYSQL个人程序

时间:2014-02-09 01:05:40

标签: java mysql sql swing jtable

嗨,首先是我的代码..

主要课程:

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main 
{
     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException 
        {
            try 
            {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } 
            catch(Exception e)
            {

            }

            LoginGUI login = new LoginGUI();
        }

}

LoginGui类:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.mysql.jdbc.Connection;

public class LoginGUI extends JFrame
{


     private String URL,username, password;
     private Login login;

     private JPanel buttonPanel;
     private JButton loginButton,
                     exit;

     public LoginGUI()
     {        
         super("Login");
         setLocationRelativeTo(null);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setLayout(new BorderLayout());
         login = new Login();

         buildButtonPanel();
         add(login, BorderLayout.CENTER);
         add(buttonPanel, BorderLayout.PAGE_END);
         setResizable(false);
         pack();
         setVisible(true);
     }

     private void buildButtonPanel() 
     {
         buttonPanel = new JPanel();

         loginButton = new JButton("Login");
         loginButton.addActionListener(new loginListener());

         exit = new JButton("Exit");
         exit.addActionListener(new exitListener());

         buttonPanel.add(loginButton);
         buttonPanel.add(exit);      
     }
     private class loginListener implements ActionListener
      {
         @Override
          public void actionPerformed (ActionEvent e)
          {         
              username = login.getUsername();
              password = login.getPassword();
              Connection con = null;
              URL = "jdbc:mysql://localhost:3306/tryingsql";

              try 
              {
                Class.forName("com.mysql.jdbc.Driver");
                con = (Connection) DriverManager.getConnection(URL, username, password);

                JOptionPane.showMessageDialog(null, "Connection Has Been Stablished. Click Ok to Continue");
                con.close();
                setVisible(false);
                javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            createAndShowGUI();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                });

              } catch (ClassNotFoundException e1) {
                JOptionPane.showMessageDialog(null, "There is a problem with the connection, try connecting again and if problem persist,"
                        + " Call Customer Server");
                System.exit(0);
            } catch (SQLException e1) {
                JOptionPane.showMessageDialog(null, "There is a problem with the Database, try connecting again and if problem persist,"
                        + " Call Customer Server");;
                System.exit(0);
            }                
          }
     }
     private class exitListener implements ActionListener
      {
         @Override
          public void actionPerformed (ActionEvent e)
          {
              JOptionPane.showMessageDialog(null, "Thanks for Using This Program");
              System.exit(0);                          
          }
      }
     public static String FormatPhoneNumber(String s)
        {
            String phoneNumber;
            phoneNumber = "" + s.charAt(0) + s.charAt(1) + s.charAt(2) + "-" + s.charAt(3) + s.charAt(4) + s.charAt(5)
                        + "-" + s.charAt(6) + s.charAt(7) + s.charAt(8) + s.charAt(9);
            return phoneNumber;
        }

     private  void createAndShowGUI() throws SQLException {
            //Create and set up the window.
            JFrame frame = new JFrame("SimpleTableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Create and set up the content pane.
            TablesGUI Tables = new TablesGUI(URL, username, password);
            Tables.setOpaque(true); //content panes must be opaque
            frame.setContentPane(Tables);

            //Display the window.
            frame.pack();
            frame.setVisible(true);

        }
}

登录课程:

import java.awt.GridLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login extends JPanel
{
    private JLabel usernameLabel, passwordLabel;
    private JTextField username;
    private JPasswordField password;



    public Login()
    {
        setLayout(new GridLayout(2, 2));

        usernameLabel = new JLabel("Username: ");
        username = new JTextField(12);

        passwordLabel = new JLabel("Password: ");
        password = new JPasswordField(12);

        add(usernameLabel);
        add(username);
        add(passwordLabel);
        add(password);
    }
    public void setUsername(String s)
    {
        username.setText(s);
    }
    public void setPassword(String s)
    {
        password.setText(s);
    }
    public String getUsername() 
    {
        String uname = "";         
        uname = username.getText();

        return uname;
    }

    @SuppressWarnings("deprecation")
    public String getPassword() 
    {
        String pass = "";
        pass = password.getText();

        return pass;
    }
}

TablesGUI类:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetMetaData;


public class TablesGUI extends JPanel
{

        private boolean DEBUG = false;

        public static String FormatPhoneNumber(String s)
        {
            String phoneNumber;
            phoneNumber = "" + s.charAt(0) + s.charAt(1) + s.charAt(2) + "-" + s.charAt(3) + s.charAt(4) + s.charAt(5)
                        + "-" + s.charAt(6) + s.charAt(7) + s.charAt(8) + s.charAt(9);
            return phoneNumber;
        }

        public TablesGUI(String url,String uname, String password) throws SQLException
        {
            super(new GridLayout(1,0));
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = (Connection) DriverManager.getConnection(url, uname, password);
                PreparedStatement statement = (PreparedStatement) conn.prepareStatement("SELECT * FROM basicinformation");
                ResultSet result = statement.executeQuery();

                final JTable table = new JTable(writeResult(result));
                table.setPreferredScrollableViewportSize(new Dimension(900, 200));
                table.setFillsViewportHeight(true);
                if (DEBUG) 
                {
                    table.addMouseListener(new MouseAdapter() 
                    {
                        public void mouseClicked(MouseEvent e) {
                        printDebugData(table);
                        }
                    });
                }
                JScrollPane scrollPane = new JScrollPane(table);
                add(scrollPane);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(TablesGUI.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        public static DefaultTableModel writeResult (ResultSet res) throws SQLException {

            ResultSetMetaData metaData = (ResultSetMetaData) res.getMetaData();

            Vector<String> columnNames = new Vector<>();
            int columnCount = metaData.getColumnCount();
            for (int column = 1; column <= columnCount; column++) {
                columnNames.add(metaData.getColumnName(column));
            }

              Vector<Vector<Object>> data = new Vector<>();
            while (res.next()) {
                Vector<Object> vector = new Vector<Object>();
                for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                    if(columnIndex == 8)
                    {
                        vector.add(FormatPhoneNumber(res.getString(columnIndex)));
                    } else if(columnIndex == 10)
                    {
                        if(res.getString(columnIndex) == null)
                        {
                            vector.add("Still Active");
                        } else
                        {
                            vector.add(res.getString(columnIndex));
                        }
                    }
                    else
                    {
                        vector.add(res.getString(columnIndex));
                    }
                }
                data.add(vector);
            }

            return new DefaultTableModel(data,columnNames);
        }

        //still working on this..
        //public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears on screen.
            //if(col > 8)
            //  return false;
            //else
           //     return true;
      //  }



        private void printDebugData(JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();

            System.out.println("Value of data: ");
            for (int i=0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j=0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
}

我的程序打开后出现的第一个窗口: http://postimg.org/image/d3raigkgd/ 用户输入用于连接到sql数据库的信息。这很好。

登录后

主窗口: http://postimg.org/image/8j9ph9q4t/ 这里的表加载了数据库中的信息。这里的一切也很好。

到目前为止,我的程序运行正常。我现在需要和想做的就是: 1st:用户在jtables上编辑内容后能够立即更新mysqldatabase。香港专业教育学院阅读有关isEditable并从setValue解雇但未能实现它,所以如果有人可以帮助我或指向一个好的教程或一些伟大的东西。

第二步:在表格下方添加一个搜索按钮,其中有一个选择框,您可以在其中选择要搜索的内容,例如ID或名称地址等,在您输入任何内容的文本字段旁边,然后当然搜索按钮。单击时,仅显示具有相同搜索词的所有客户或所有客户。 (或者只是一个搜索框加上选择事物和表更新,因为用户在搜索框中键入任何内容,就像用户选择名称并开始键入D一样,表格会显示所有带有D的名称然后如果用户键入De或其他任何名称显示所有“DE”客户等等。

第3名:在左侧我想要一个添加(添加一个客户)和删除按钮(更多的按钮,但将来的那个)。添加客户将显示一个空行,用户将填写该行,然后添加到表和数据库。删除按钮应仅在选择客户/客户时起作用。

现在要记住的事情,是的,我是java新数据库的新手,而不是新的新的,但最近我开始了。我不是java的新手。我只是想尽可能多地学习java中的东西,数据库是我以前从未使用过的东西。此外,我不是要求你为我完成程序大声笑所有即时通讯要求是想法,相关的代码,教程或事物id需要使我想要的事情发生。提前谢谢。

也很遗憾没有在我的代码中发表评论,我通常不会在以后输入评论。对我的代码的任何建议也很受欢迎。

2 个答案:

答案 0 :(得分:0)

首先,从表中更新数据库似乎对我不利,因为您希望能够通过某些文本字段添加客户。

要完成第3个问题,您可以让Add按钮打开一个模式JDialog,允许您输入字段,然后在输入数据时,您可以更新数据库。此外,如果成功添加数据,您只需将该行添加到表中即可。

Delete按钮相同。如果成功删除了一行,请从表中删除它。只需循环查找表格中的行,removeRow

对于第二个问题,您可以使用RowFilter来过滤表格。从this question运行示例以获得简单用法。另请参阅Row Filter的API。您可以添加DocumentListener来监听文本字段的更改。从链接的示例中,使用DocumentListener

看起来像这样
    jtfFilter.getDocument().addDocumentListener(new DocumentListener(){
        String text = jtfFilter.getText();
        @Override
        public void insertUpdate(DocumentEvent e) {
            if (text.trim().length() == 0) {
                rowSorter.setRowFilter(null);
            } else {
                rowSorter.setRowFilter(RowFilter.regexFilter(text));
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            if (text.trim().length() == 0) {
                rowSorter.setRowFilter(null);
            } else {
                rowSorter.setRowFilter(RowFilter.regexFilter(text));
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {}

    });

答案 1 :(得分:0)

<强> 1)

要更新数据库,您可以使用AbstractTableModel's方法。请参阅AbstractTableModel


<强> 2)

要搜索来自JTable的数据,您可以使用以下内容:

public class JTableSearchAndHighlight extends JFrame {

   private JTextField searchField;
   private JTable table;
   private JPanel panel;
   private JScrollPane scroll;

   public JTableSearchAndHighlight() {

     initializeInventory();
   }

private void initializeInventory() {

    panel = new JPanel();

    searchField = new JTextField();

    panel.setLayout(null);

    final String[] columnNames = {"Name", "Surname", "Age"};

    final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Max", "Dumbass", "10"}, {"Melanie", "Martin", "500"},
                            {"Jollibe", "Mcdonalds", "15"}};

    table = new JTable(data, columnNames);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);

    scroll = new JScrollPane(table);
    scroll.setBounds(0, 200, 900, 150);

    searchField.setBounds(10, 100, 150, 20);
    searchField.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            String value = searchField.getText();

            for (int row = 0; row <= table.getRowCount() - 1; row++) {

                for (int col = 0; col <= table.getColumnCount() - 1; col++) {

                    if (value.equals(table.getValueAt(row, col))) {

                        // this will automatically set the view of the scroll in the location of the value
                        table.scrollRectToVisible(table.getCellRect(row, 0, true));

                        // this will automatically set the focus of the searched/selected row/value
                        table.setRowSelectionInterval(row, row);

                        for (int i = 0; i <= table.getColumnCount() - 1; i++) {

                            table.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer());
                        }
                    }
                }
            }
        }
    });

    panel.add(searchField);
    panel.add(scroll);

    getContentPane().add(panel);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Inventory Window");
    setSize(900, 400);
    setLocationRelativeTo(null);
    setVisible(true);
}

private class HighlightRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        // everything as usual
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        // added behavior
        if(row == table.getSelectedRow()) {

            // this will customize that kind of border that will be use to highlight a row
            setBorder(BorderFactory.createMatteBorder(2, 1, 2, 1, Color.BLACK));
        }

        return this;
    }
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        public void run() {

            new JTableSearchAndHighlight();
        }
    });
  }
}

第3)

您可以像这样添加或删除JTable中的数据:

如果您使用DefaultTableModel:

,则可以执行此操作
DefaultTableModel dtm = new DefaultTableModel(products, colName);
table = new JTable(dtm);

现在您可以添加和删除行:

dtm.removeRow(0); //remove first row
dtm.addRow(new Object[]{...});//add row

如果要根据ID删除行,可以搜索具有该ID的行,然后将其删除:

String searchedId = "867954";//ID of the product to remove from the table
int row = -1;//index of row or -1 if not found

//search for the row based on the ID in the first column
for(int i=0;i<dtm.getRowCount();++i)
    if(dtm.getValueAt(i, 0).equals(searchedId))
    {
        row = i;
        break;
    }

if(row != -1)
    dtm.removeRow(row);//remove row

else
    ...//not found

有用的链接

How to Use Tables