简体   繁体   English

从JTextField中检索文本

[英]Retrieving text from JTextField

The concept of my code is that, it will initially retrieve distinct names from a column 'tname' of my access database table 'try'. 我的代码的概念是,它最初将从我的访问数据库表'try'的列'tname'中检索不同的名称。 It will add those items in a combobox. 它会将这些项目添加到组合框中。 Once we select an item in the combo box, the data of the row containing tname as the selected item is retrieved and showed in textfields. 一旦我们在组合框中选择了一个项目,就会检索包含tname作为所选项目的行的数据并显示在文本字段中。 Then I will make some changes to the text field content. 然后我将对文本字段内容进行一些更改。 After that, if I click 'Save' button, then all the data of the row containing tname as the selected combobox item must be updated with the new content in the textfields. 之后,如果单击“保存”按钮,则必须使用文本字段中的新内容更新包含tname作为所选组合框项目的行的所有数据。

Everything goes fine, except the last one. 一切顺利,除了最后一个。 When I click 'save' it considers only the previous text(the one intially retrieved from the database when we select combobox) and not the changes made to it. 当我单击“保存”时,它只考虑以前的文本(当我们选择组合框时从数据库中初步检索的文本),而不考虑对其进行的更改。 Kindly help me to diagnose the problem. 请帮我诊断问题。

Thanks in advance. 提前致谢。

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.Date;
import java.sql.*;
import java.text.*;

public class gut implements ActionListener
{
JComboBox ctn;
JTextField cm,exd,stk,cst,sup,snum,r;
String stn,scm,sexd,sst,scst,ssup,ssnum,sr,icm,iexd,istk,icst,isup,isnum,ir;
JLabel lt,lc,le,ls,lcs,lsp,lspn,lr;
JButton s;
JFrame gp=new JFrame();

public gut()
{
gp.setSize(500,500);
gp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

gp.setLayout(null);

lt=new JLabel("Tablet Name",JLabel.RIGHT);
lc=new JLabel("Composition",JLabel.RIGHT);
le=new JLabel("Expiry Date (dd/mm/yyyy)",JLabel.RIGHT);
ls=new JLabel("Stock",JLabel.RIGHT);
lcs=new JLabel("Cost",JLabel.RIGHT);
lsp=new JLabel("Supplier",JLabel.RIGHT);
lspn=new JLabel("Supplier Number",JLabel.RIGHT);
lr=new JLabel("Rack",JLabel.RIGHT);

lt.setBounds(100,120,120,20);
lc.setBounds(100,140,120,20);
le.setBounds(60,160,160,20);
ls.setBounds(100,180,120,20);
lcs.setBounds(100,200,120,20);
lsp.setBounds(100,220,120,20);
lspn.setBounds(100,240,120,20);
lr.setBounds(100,260,120,20);

ctn=new JComboBox();
cm=new JTextField();
exd=new JTextField();
stk=new JTextField();
cst=new JTextField();
sup=new JTextField();
snum=new JTextField();
r=new JTextField();


ctn.setBounds(240,120,120,20);
cm.setBounds(240,140,120,20);
exd.setBounds(240,160,120,20);
stk.setBounds(240,180,120,20);
cst.setBounds(240,200,120,20);
sup.setBounds(240,220,120,20);
snum.setBounds(240,240,120,20);
r.setBounds(240,260,120,20);

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select DISTINCT tname from try");

while(rs.next())
{
 ctn.addItem(rs.getString("tname"));
}

conn.close();
}
catch(Exception e)
{
}

gp.add(lt);gp.add(ctn);
gp.add(lc);gp.add(cm);
gp.add(le);gp.add(exd);
gp.add(ls);gp.add(stk);
gp.add(lcs);gp.add(cst);
gp.add(lsp);gp.add(sup);
gp.add(lspn);gp.add(snum);
gp.add(lr);gp.add(r);

ctn.addActionListener(this);
s=new JButton("Save");
s.setBounds(200,300,100,20);
gp.add(s);
s.addActionListener(this);




gp.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
String act=evt.getActionCommand();

String scb=(String)ctn.getSelectedItem();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from try where tname='"+scb+"'");
SimpleDateFormat formatter=new SimpleDateFormat("dd/MM/yyyy");

while(rs.next())
{
icm=rs.getString("composition");
iexd=formatter.format(rs.getDate("exdate"));
istk=Integer.toString(rs.getInt("stock"));
icst=rs.getString("cost");
isup=rs.getString("sup");
isnum=rs.getString("supnum");
ir=rs.getString("rack");
}

cm.setText(icm);
exd.setText(iexd);
stk.setText(istk);
cst.setText(icst);
sup.setText(isup);
snum.setText(isnum);
r.setText(ir);


conn.close();
}
catch(Exception e)
{
System.out.println(e);
}


if(act.equals("Save"))
{
scm=cm.getText();
sexd=exd.getText();
sst=stk.getText();
scst=cst.getText();
ssup=sup.getText();
ssnum=snum.getText();
sr=r.getText();
System.out.println(scm+","+sexd+","+sst+","+scst+","+ssup+","+ssnum+","+sr);
try
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
PreparedStatement ps=conn.prepareStatement("UPDATE try set composition=?,exdate=?,stock=?,cost=?,sup=?,supnum=?,rack=? where 

tname=?");

ps.setString(1,scm);
ps.setString(2,sexd);
ps.setString(3,sst);
ps.setString(4,scst);
ps.setString(5,ssup);
ps.setString(6,ssnum);
ps.setString(7,sr);
ps.setString(8,scb);

ps.executeUpdate();

JOptionPane.showMessageDialog(null,"Your entry has been stored successfully!!!");

}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error!Try again!");
System.out.println(e);

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

}

Your actionPerformed() function retrieves the information from the database every time. actionPerformed()函数每次都从数据库中检索信息。 If you press the Save button it will first retrieve the information and then save the information if the action command is "Save". 如果按“保存”按钮,它将首先检索信息,然后在动作命令为“保存”时保存信息。 This is why you always get the information that's currently in the database from getText() when pressing the Save button. 这就是为什么在按下Save按钮时总是从getText()获取当前数据库中的信息的原因。

Make a different function / actionListener to execute when the Save button is pressed or take the part of the code that updates the text fields else where. 在按下“保存”按钮时执行不同的函数/ actionListener,或者将代码的一部分更新为其他位置的文本字段。

Try something like this instead: 尝试这样的事情:

JButton saveButton = new JButton( new AbstractAction("save") {
        @Override
        public void actionPerformed( ActionEvent e ) {
            // Save the info here or just call a function that will.
        }
    });

The problem is that every time you hit the "Save" button you are retrieving the information from the database over again, so, you overwrite the TextFields and then you read from the TexFields content. 问题是,每次点击“保存”按钮,您都会再次从数据库中检索信息,因此,您将覆盖TextFields,然后从TexFields内容中读取。 Try to take out this part: 尝试取出这部分:

 try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection conn = DriverManager.getConnection

            ("jdbc:odbc:vasantham", "", "");
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("select * from try where tname='"
                    + scb + "'");
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

            while (rs.next()) {
                icm = rs.getString("composition");
                iexd = formatter.format(rs.getDate("exdate"));
                istk = Integer.toString(rs.getInt("stock"));
                icst = rs.getString("cost");
                isup = rs.getString("sup");
                isnum = rs.getString("supnum");
                ir = rs.getString("rack");
            }

            cm.setText(icm);
            exd.setText(iexd);
            stk.setText(istk);
            cst.setText(icst);
            sup.setText(isup);
            snum.setText(isnum);
            r.setText(ir);

            conn.close();
        } catch (Exception e) {
            System.out.println(e);
        }

from the action performed method. 从动作执行的方法。

Every time your action event is fired, you read data from DB and write it into the textfields. 每次触发动作事件时,都会从DB读取数据并将其写入文本字段。 You can change that text and it will be displayed correctly in your textfields. 您可以更改该文本,它将在您的文本字段中正确显示。 But when you click save, all your changes are overwritten with the DB values again. 但是当您单击“保存”时,所有更改都会再次被DB值覆盖。

So you have to separate the functionalities "read from DB" and "write changes". 因此,您必须将“从DB读取”和“写入更改”的功能分开。

edit: oops, too slow.. 编辑:哎呀,太慢..

On top of what everybody else has already said, if you REALLY want to use a single action listener, you are going to need to work out which action has actually occurred. 除了其他人已经说过的内容之外,如果您真的想要使用单个动作侦听器,那么您将需要确定实际发生了哪个动作。

You could check the source of the ActionEvent ( evt.getSource() ) or, more appropriately, you could assign a action command to each component using the action listener. 您可以检查ActionEvent的源( evt.getSource() ),或者更恰当地说,您可以使用动作侦听器为每个组件分配一个动作命令。

Check out JComboBox.setActionCommand(...) and JButton.setActionCommand(...) 查看JComboBox.setActionCommand(...)JButton.setActionCommand(...)

After that, it's a simple case of checking the ActionEvent.getActionCommand() property to determine the correct action to take. 之后,检查ActionEvent.getActionCommand()属性以确定要采取的正确操作是一个简单的例子。

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

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