【问题标题】:Passing variable from JFrame to SqlQueryClass将变量从 JFrame 传递到 SqlQueryClass
【发布时间】:2015-04-07 12:42:32
【问题描述】:

我已经设置了 3 个框架,Frame1-->我有 2 个选项从 TextField1TextField2 [即(姓名,姓氏)] 查询所有或查询提供的变量,并根据 textFields 显示数据。

我尝试使用静态文本字段,但我只能查询一次,因为文本字段在输入时初始化文本,我尝试将变量传递给查询类中的构造函数,但仍然没有运气。

也许有一种方法,一旦将文本输入到静态文本字段中,文本字段就可以刷新?

请帮忙!

这就是我想要达到的目标。

  import java.awt.Color;
  import java.awt.Container;
  import java.awt.Font;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.sql.ResultSet;

  import javax.security.auth.Refreshable;
  import javax.swing.BorderFactory;
  import javax.swing.ImageIcon;
  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JTextField;
  import javax.swing.border.Border;

  import com.mysql.jdbc.Statement;

  @SuppressWarnings("serial")
  public class HistoryOptions extends JFrame implements ActionListener/
{   
private Statement stmt = null;
private Container content;

private JPanel optionPanel;
private Border lineBorder;
private JLabel singleLabel = new JLabel("View Single Patient");
private JLabel orLabel = new JLabel("OR");

private JLabel FirstNLabel=new JLabel("Name: ");
private JLabel LastNLabel=new JLabel("Surname: ");
public static JTextField FirstNTF = new JTextField();
public static JTextField LastNTF=new JTextField();

private  QueryTableModel TableModel= new QueryTableModel();

private JButton viewAllBT = new JButton("View All Patients");
private JButton viewSingleBT = new JButton("View ");
private JButton clearButton  = new JButton("Clear ");

//private String Fname;
//private String Lname;

public HistoryOptions( String aTitle)
{   
    super(aTitle);
    setEnabled(true);

    content=getContentPane();
    content.setLayout(null);
    content.setBackground(Color.lightGray);

    JPanel backgroundPanel = new JPanel();
    ImageIcon background = new ImageIcon("img/clouds.jpg");
    JLabel backgroundLabel = new JLabel();
    backgroundLabel.setIcon(background);
    backgroundPanel.add(backgroundLabel);

    optionPanel = new JPanel();
    optionPanel.setLayout(null);

    Font myFont = new Font("Arial", Font.BOLD, 20);
    Font myFont2 = new Font("Arial", Font.ITALIC, 15);


    lineBorder = BorderFactory.createEtchedBorder(15, Color.blue, Color.blue);

    optionPanel.add(FirstNLabel);
    FirstNLabel.setFont(myFont2);
    optionPanel.add(FirstNTF);
    optionPanel.add(LastNLabel);
    LastNLabel.setFont(myFont2);
    optionPanel.add(LastNTF);

    optionPanel.add(singleLabel);
    optionPanel.add(orLabel);

    optionPanel.add(viewAllBT);
    optionPanel.add(viewSingleBT);
    optionPanel.add(clearButton);

    optionPanel.setBounds(300,155,340,225);

    singleLabel.setBounds(70,5,180,30);//370,120
    singleLabel.setFont(myFont);

    FirstNLabel.setBounds(15,40,100,30);//300,170
    FirstNTF.setBounds(120,40,200,30);//400,170
    LastNLabel.setBounds(15,75,100,30);//300,205
    LastNTF.setBounds(120,72,200,30);//400,205

    viewSingleBT.setBounds(120,107,98,30);//400,240
    clearButton.setBounds(220,107,98,30);//502,240

    orLabel.setBounds(155,145,50,30);//430,290
    orLabel.setFont(myFont);
    viewAllBT.setBounds(15,180,305, 30);//300,330

    backgroundPanel.setBounds(0,-10,940,640);

    viewAllBT.addActionListener(this);
    viewSingleBT.addActionListener(this);
    clearButton.addActionListener(this);


    content.add(optionPanel);
    content.add(backgroundPanel);

    optionPanel.setBorder(BorderFactory.createTitledBorder(lineBorder,"Options"));

    setSize(938,630);//770,600
    setVisible(true);

    //TableModel.refreshFromDB5(stmt);
}


public void actionPerformed(ActionEvent e)
{
    Object target=e.getSource();
    ResultSet rs=null;
    String cmd = null;
    if (target == clearButton)
    {

        FirstNTF.setText("");
        LastNTF.setText("");



    }
    if(target == viewAllBT){
        AllPatientHistoryDB ph = new AllPatientHistoryDB("All Patients History Database");
        ph.setVisible(true);

    }
    if(target == viewSingleBT){

        String Fname=FirstNTF.getText();
        String Lname=LastNTF.getText();

        SinglePatientHistoryDB sph = new SinglePatientHistoryDB("Single Patient History Database");
        sph.setVisible(true);

        //QueryTableModel qtmf = new QueryTableModel(Fname,Lname);
        //qtm.setName(Fname);
        //qtm.setSurname(Lname);
    }
}

}

SinglePatient 类

 import java.awt.Color;
 import java.awt.Container;
 import java.awt.Dimension; 
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;

 import javax.swing.BorderFactory;
 import javax.swing.ImageIcon;
 import javax.swing.JButton;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JScrollPane;
 import javax.swing.JTable;
 import javax.swing.JTextArea;
 import javax.swing.JTextField;
 import javax.swing.border.Border;

 @SuppressWarnings("serial")
 public class SinglePatientHistoryDB extends JFrame implements       ActionListener
 {  
        String cmd = null;
        private Connection con = null;
        private Statement stmt = null;
        private ResultSet rs = null;

        private Container content;

private JPanel detailsPanel;
private JPanel backgroundP;

private JScrollPane dbContentsPanel;

private Border lineBorder;
private JLabel IDLabel=new JLabel("Select ID to UPDATE: ");
private JLabel HDateLabel=new JLabel("DATE: ");
private JLabel FirstNameLabel=new JLabel("NAME: ");
private JLabel LastNameLabel=new JLabel("SURNAME: ");
private JLabel HistoryLabel=new JLabel("HISTORY INFO: ");

private JTextField IDTF = new JTextField();
private JTextField HDateTF=new JTextField();
private JTextField FirstNameTF= new JTextField();
private JTextField LastNameTF=new JTextField();
private JTextArea HistoryTF=new JTextArea();

private static QueryTableModel TableModel = new QueryTableModel();
private JTable TableofDBContents=new JTable(TableModel);
private JButton updateButton = new JButton("Update");
private JButton insertButton = new JButton("Insert");
private JButton clearButton  = new JButton("Clear All");

private JTextField FirstNTF =new JTextField();
private JTextField LastNTF= new JTextField();

//private String Fname;
//private String Lname;


public SinglePatientHistoryDB( String aTitle)
{   
    //setting up the GUI
    super(aTitle);
    //Fname=FirstNTF.getText(FirstNTF);
    //Lname=LastNTF.getText();

    setEnabled(true);

    initiate_db_conn();
    //add the 'main' panel to the Internal Frame
    content=getContentPane();
    content.setLayout(null);
    content.setBackground(Color.lightGray);
    lineBorder = BorderFactory.createEtchedBorder(15, Color.blue, Color.blue);

    JPanel backgroundP = new JPanel();
    ImageIcon backg = new ImageIcon("img/historyBACK.jpg");
    JLabel backgroundL = new JLabel();
    backgroundL.setIcon(backg);
    backgroundP.add(backgroundL);

    content.add(IDLabel);       
    content.add(IDTF);
    content.add(HDateLabel);
    content.add(HDateTF);
    content.add(FirstNameLabel);        
    content.add(FirstNameTF);
    content.add(LastNameLabel);         
    content.add(LastNameTF);
    content.add(HistoryLabel);      
    content.add(HistoryTF);

    content.add(insertButton);
    content.add(updateButton);
    content.add(clearButton);

    IDLabel.setBounds(540,370,120,25);
    IDTF.setBounds(675,370,100,25);

    HDateLabel.setBounds(35,370,100,25);
    HDateTF.setBounds(135,370,160,25);
    FirstNameLabel.setBounds(35,400,100,25);
    FirstNameTF.setBounds(135,400,160,25);
    LastNameLabel.setBounds(35,430,100,25);
    LastNameTF.setBounds(135,430,160,25);
    HistoryLabel.setBounds(35,475,100,25);
    HistoryTF.setBounds(135,475,640,75);

    updateButton.setBounds(780,370,100, 25);
    insertButton.setBounds(780,475,100,25);
    clearButton.setBounds(780,505,100,25);


    insertButton.addActionListener(this);
    updateButton.addActionListener(this);
    clearButton.addActionListener(this);


    TableofDBContents.setPreferredScrollableViewportSize(new Dimension(900, 300));

    dbContentsPanel=new JScrollPane(TableofDBContents,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    dbContentsPanel.setBackground(Color.lightGray);
    dbContentsPanel.setBorder(BorderFactory.createTitledBorder(lineBorder,"Patient History"));

    backgroundP.setBounds(0,-10,940,640);
    dbContentsPanel.setSize(850, 300);
    dbContentsPanel.setLocation(35, 40);

    //content.add(detailsPanel);
    content.add(dbContentsPanel);
    content.add(backgroundP);

    setSize(938,630);//770,600
    setVisible(true);

    TableModel.refreshFromDB5(stmt);
}

public void initiate_db_conn()
{
    try
    {
        // Load the JConnector Driver
        Class.forName("com.mysql.jdbc.Driver");
        // Specify the DB Name
        String url="jdbc:mysql://localhost:3306/PatientHistoryDB";
        // Connect to DB using DB URL, Username and password
        con = DriverManager.getConnection(url, "root", "Pass"); 
        //Create a generic statement which is passed to the TestInternalFrame1
        stmt = con.createStatement();
    }
    catch(Exception e)
    {
        System.out.println("Error: Failed to connect to database\n"+e.getMessage());
    }
}

public void actionPerformed(ActionEvent e)
{
    Object target=e.getSource();
    ResultSet rs=null;
    String cmd = null;
    if (target == clearButton)
    {
        IDTF.setText("");
        HDateTF.setText("");
        FirstNameTF.setText("");
        LastNameTF.setText("");
        HistoryTF.setText("");

    }

    if (target == insertButton)
    {        
        try
        {
            String updateTemp ="INSERT INTO hdetails VALUES("+null+",'"+HDateTF.getText()+"','"+FirstNameTF.getText()+"','"+LastNameTF.getText()+"','"+HistoryTF.getText()+"');";




            stmt.executeUpdate(updateTemp);

        }
        catch (SQLException sqle)
        {
            System.err.println("Error with  insert:\n"+sqle.toString());
        }
        finally
        {
            TableModel.refreshFromDB5(stmt);
        }
    }

    if (target == updateButton)
    {       
        try
        {           
            String updateTemp ="UPDATE hdetails SET " + 
                    "FirstName = '"+FirstNameTF.getText()+      
                    "', LastName = '"+LastNameTF.getText()+      
                    "', History = '"+HistoryTF.getText()+                  
                    "', HDate ='"+HDateTF.getText()+              
                    "' where id = "+IDTF.getText();


            stmt.executeUpdate(updateTemp);
            //these lines do nothing but the table updates when we access the db.
            rs = stmt.executeQuery("SELECT * from hdetails ");
            rs.next();
            rs.close(); 
        }
        catch (SQLException sqle){
            System.err.println("Error with  update:\n"+sqle.toString());
        }
        finally{
            TableModel.refreshFromDB5(stmt);
        }
    }}

}

还有 ViewAllHistory 类,但它工作正常,所以不需要放在这里。

这就是查询类

 import java.sql.Connection;
 import java.sql.ResultSet;  
 import java.sql.ResultSetMetaData;
 import java.sql.Statement;
 import java.util.Vector;

 import javax.swing.JTextField;
 import javax.swing.table.AbstractTableModel;

 @SuppressWarnings("serial")
 class QueryTableModel extends AbstractTableModel
 {
 Vector modelData; //will hold String[] objects
 int colCount;
 String[] headers=new String[0] ;
 Connection con;
 Statement stmt = null;

 String[] record;
 ResultSet rs = null;

 //private JTextField fnameTF = new     JTextField(HistoryOptions.FirstNTF.getText());
 //private JTextField lnameTF = new   JTextField(HistoryOptions.LastNTF.getText());


public QueryTableModel(){//(String Fname,String Lname){


    modelData = new Vector();
}//end constructor QueryTableModel


public String getColumnName(int i){
    return headers[i];
}   
public int getColumnCount(){
    return colCount;
}

public int getRowCount(){
    return modelData.size();
}

public Object getValueAt(int row, int col){
    return ((String[])modelData.elementAt(row))[col];
}

 // public void setName(String Fname) {
 //     this.fnameTF.setText(Fname);  
 //     }
 //     
 //     public void setSurname(String Lname) {
 //     this.lnameTF.setText(Lname);}

 public void refreshFromDB( Statement stmt1)
 {
    //modelData is the data stored by the table
    //when set query is called the data from the 
    //DB is queried using “SELECT * FROM myInfo” 
    //and the data from the result set is copied 
    //into the modelData. Every time refreshFromDB is
    //called the DB is queried and a new 
    //modelData is created  

    modelData = new Vector();
    stmt = stmt1;
    try{
        //Execute the query and store the result set and its metadata
        rs = stmt.executeQuery("SELECT * FROM Details");

        ResultSetMetaData meta = rs.getMetaData();

        //to get the number of columns
        colCount = meta.getColumnCount(); 
        // Now must rebuild the headers array with the new column names
        headers = new String[colCount];

        for(int h = 0; h<colCount; h++)
        {
            headers[h] = meta.getColumnName(h+1);
        }//end for loop

        // fill the cache with the records from the query, ie get all the rows

        while(rs.next())
        {
            record = new String[colCount];
            for(int i = 0; i < colCount; i++)
            {
                record[i] = rs.getString(i+1);
            }//end for loop
            modelData.addElement(record);
        }// end while loop
        fireTableChanged(null); //Tell the listeners a new table has arrived.
    }//end try clause
    catch(Exception e) {
                System.out.println("Error with refreshFromDB Method\n"+e.toString());
    } // end catch clause to query table

}//end refreshFromDB method

 public void refreshFromDB2( Statement stmt2)
 {
    //modelData is the data stored by the table
    //when set query is called the data from the 
    //DB is queried using “SELECT * FROM myInfo” 
    //and the data from the result set is copied 
    //into the modelData. Every time refreshFromDB is
    //called the DB is queried and a new 
    //modelData is created  

    modelData = new Vector();
    stmt = stmt2;
    try{
        //Execute the query and store the result set and its metadata
        rs = stmt.executeQuery("SELECT * FROM feeds");

        ResultSetMetaData meta = rs.getMetaData();

        //to get the number of columns
        colCount = meta.getColumnCount(); 
        // Now must rebuild the headers array with the new column names
        headers = new String[colCount];

        for(int h = 0; h<colCount; h++)
        {
            headers[h] = meta.getColumnName(h+1);
        }//end for loop

        // fill the cache with the records from the query, ie get all the rows

        while(rs.next())
        {
            record = new String[colCount];
            for(int i = 0; i < colCount; i++)
            {
                record[i] = rs.getString(i+1);
            }//end for loop
            modelData.addElement(record);
        }// end while loop
        fireTableChanged(null); //Tell the listeners a new table has arrived.
    }//end try clause
    catch(Exception e) {
                System.out.println("Error with refreshFromDB2 Method\n"+e.toString());
    } // end catch clause to query table

}//end refreshFromDB method

 public void refreshFromDB3( Statement stmt3)
 {
    //modelData is the data stored by the table
    //when set query is called the data from the 
    //DB is queried using “SELECT * FROM myInfo” 
    //and the data from the result set is copied 
    //into the modelData. Every time refreshFromDB is
    //called the DB is queried and a new 
    //modelData is created  

    modelData = new Vector();
    stmt = stmt3;
    try{
        //Execute the query and store the result set and its metadata
        rs = stmt.executeQuery("SELECT * FROM bdetails");

        ResultSetMetaData meta = rs.getMetaData();

        //to get the number of columns
        colCount = meta.getColumnCount(); 
        // Now must rebuild the headers array with the new column names
        headers = new String[colCount];

        for(int h = 0; h<colCount; h++)
        {
            headers[h] = meta.getColumnName(h+1);
        }//end for loop

        // fill the cache with the records from the query, ie get all the rows

        while(rs.next())
        {
            record = new String[colCount];
            for(int i = 0; i < colCount; i++)
            {
                record[i] = rs.getString(i+1);
            }//end for loop
            modelData.addElement(record);
        }// end while loop
        fireTableChanged(null); //Tell the listeners a new table has arrived.
    }//end try clause
    catch(Exception e) {
                System.out.println("Error with refreshFromDB3 Method\n"+e.toString());
    } // end catch clause to query table

}//end refreshFromDB method

    public void refreshFromDB4( Statement stmt4)
    {
        //modelData is the data stored by the table
        //when set query is called the data from the 
        //DB is queried using “SELECT * FROM myInfo” 
        //and the data from the result set is copied 
        //into the modelData. Every time refreshFromDB is
        //called the DB is queried and a new 
        //modelData is created  

        modelData = new Vector();
        stmt = stmt4;
        try{
            //Execute the query and store the result set and its metadata
            rs = stmt.executeQuery("SELECT * FROM hdetails");

            ResultSetMetaData meta = rs.getMetaData();

            //to get the number of columns
            colCount = meta.getColumnCount(); 
            // Now must rebuild the headers array with the new column names
            headers = new String[colCount];

            for(int h = 0; h<colCount; h++)
            {
                headers[h] = meta.getColumnName(h+1);
            }//end for loop

            // fill the cache with the records from the query, ie get all the rows

            while(rs.next())
            {
                record = new String[colCount];
                for(int i = 0; i < colCount; i++)
                {
                    record[i] = rs.getString(i+1);
                }//end for loop
                modelData.addElement(record);
            }// end while loop
            fireTableChanged(null); //Tell the listeners a new table has arrived.
        }//end try clause
        catch(Exception e) {
                    System.out.println("Error with refreshFromDB4 Method\n"+e.toString());
        } // end catch clause to query table

    }//end refreshFromDB method

            public void refreshFromDB5( Statement stmt5)//,String Fname,String Lname)
            {


                modelData = new Vector();
                stmt = stmt5;

                //fname.setText(Fname);
                //lname.setText(Lname);

                //String first=fnameTF.getText();
                //String last=lnameTF.getText();
                try{
                    //Execute the query and store the result set and its metadata
                    //rs = stmt.executeQuery("SELECT * FROM hdetails where FirstName='"+first+"' and LastName='"+last+"'"); // pasing all variables for single user
                  rs = stmt.executeQuery("SELECT * FROM hdetails where FirstName='Stacy' and LastName='McDonald'");

                    ResultSetMetaData meta = rs.getMetaData();

                    //to get the number of columns
                    colCount = meta.getColumnCount(); 
                    // Now must rebuild the headers array with the new column names
                    headers = new String[colCount];

                    for(int h = 0; h<colCount; h++)
                    {
                        headers[h] = meta.getColumnName(h+1);
                    }//end for loop

                    // fill the cache with the records from the query, ie get all the rows

                    while(rs.next())
                    {
                        record = new String[colCount];
                        for(int i = 0; i < colCount; i++)
                        {
                            record[i] = rs.getString(i+1);
                        }//end for loop
                        modelData.addElement(record);
                    }// end while loop
                    fireTableChanged(null); //Tell the listeners a new table has arrived.
                }//end try clause
                catch(Exception e) {
                            System.out.println("Error with refreshFromDB5 Method\n"+e.toString());
                } // end catch clause to query table

            }//end refreshFromDB method


   }// end class QueryTableModel

【问题讨论】:

    标签: java swing jdbc textfield


    【解决方案1】:

    你为什么说三个 JFrame?其他两个框架卖什么?? 但是我认为您需要使用按钮并按照in this document 的说明管理 onClick 事件。处理事件,您可以使用 setText(String text) 方法修改文本字段的内容。 如果您仍然有问题,请详细说明您的问题,并说明您的所有代码,而不仅仅是一小部分。

    【讨论】:

    • Frame1 = Frame2 和 Frame3 之间的选项,两者都有不同的结构和查询。
    【解决方案2】:

    以下方法应该有效:

    public class Builder {
      JTextField firstNameTextField = new JTextField();
      JTextField lastNameTextField = new JTextField();
    
      //constructor of Options should take the TextFields and add them to the JFrame
      Options options = new Options(firstNameTextField, lastNameTextField);
    
      //constructor of QueryTableModel should take the TextFields to process on them
      QueryTableModel queryTableModel = new QueryTableModel(firstNameTextField, lastNameTextField);
    }
    
    public class Options extends JFrame {
      public Options(JTextField firstNameTextField, JTextField lastNameTextField) {
        add(firstNameTextField);
        add(lastNameTextField);
      }
    }
    
    public class QueryTableModel {
      private JTextField firstNameTextField;
      private JTextField lastNameTextField;
    
      public QueryTableModel(JTextField firstNameTextField, JTextField lastNameTextField) {
        this.firstNameTextField = firstNameTextField;
        this.lastNameTextField = lastNameTextField;
      }
    
      public void refreshFromDb(Statement stmt) {
        String first = firstNameTextField.getText();
        String last = lastNameTextField.getText();
        rs = stmt.executeQuery("SELECT * FROM hdetails where FirstName='"+first+"' and LastName='"+last+"'");
      }
    }
    

    【讨论】:

    • 不幸的是,我的项目总共包含 16 个类,并且我有一个带有 6 个方法(refreshFromDB1、2、3、4、5、6)的查询类,它们的作用不同,所以如果我添加实例 QueryTableModel queryTableModel = new QueryTableModel(firstNameTextField, lastNameTextField);那么它将影响所有其他没有这些 TF 的类。
    【解决方案3】:

    当将值从静态文本字段传递到查询类时,将 getText() 放入公共函数中,然后文本字段总是在单击按钮之前亮起。工作解决方案。

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2020-04-14
      相关资源
      最近更新 更多