我试图制作一个Swing用户界面,它有一个结构,因为它从用户那里获取一个产品(jtf1),并且在数据库中它的价格被保存,所以在单击JButton之后,我想在另一个文本字段(jtf2)显示产品的价格:
import javax.swing.*;
import java.sql.*;
import java.sql.*;
import java.awt.event.*;
import java.awt.*;
class Swingui implements ActionListener
{
JFrame jf=new JFrame("PRODUCT DETAILS");
JLabel jl1=new JLabel("Product:");
JTextField jtf1=new JTextField();
JTextField jtf2=new JTextField();
JLabel jl2=new JLabel("Price:");
JButton jb=new JButton("enter");
Swingui()
{
jf.setSize(500,500);
jf.setVisible(true);
jf.setLayout(null);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jl1.setBounds(50,70,100,30);
jf.add(jl1);
jtf1.setBounds(50,100,100,30);
jf.add(jtf1);
jl2.setBounds(50,150,100,30);
jf.add(jl2);
jb.setBounds(50,180,100,30);
jf.add(jb);
jtf2.setBounds(50,200,100,30);
jf.add(jtf2);
jb.addActionListener(this);}
public static void main(String arg[])
{new Swingui();}
public void actionPerformed(ActionEvent ae){
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/product";
Connection con=DriverManager.getConnection(url,"root","");
Statement stmt=con.createStatement();
String qry="select price from price where good='"+jtf1.getText().toString()+"'";
double price=stmt.execute(qry);
String s;
String.valueof(price);
jtf2.setText(s);
}
catch(Exception e)
{e.printStackTrace();}
}
}
数据库详细信息:Database=product table=price列为(以卢比为单位):好价格gold10gm=35000 dollar=78
首先,您的代码需要围绕这一点进行修改才能编译和运行,因为execute方法返回布尔值,而您接受的是Double
ResultSet resultSet= stmt.executeQuery(qry);
int price =0;
while(resultSet.next()){
price = rs.getInt("id");
}
相应地更新代码并分配给第二个文本框。