场景是,有组合框和2个文本字段。 Combobox项目(模型)从数据库中获取并动态更新Combobox。 我已经完成了。
现在,当用户从Combobox中选择任何项目(模型)时,我需要这样做,然后应在文本字段中更新其名称和价格。
怎么做?
//此代码只有一个文本字段,我将在之后制作。
public class Purchases extends JFrame {
private JPanel contentPane;
private JTextField textField;
JComboBox comboBox = new JComboBox();
String model, name;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Purchases frame = new Purchases();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Purchases() {
try {
String host;
host = "jdbc:mysql://localhost:3306/sfs_electronics";// [root on Default schema]";
String uName = "root";
String uPass= "";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement( );
String SQL = "SELECT * FROM purchases";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
model= rs.getString("Model");
name= rs.getString("Name");
comboBox.addItem(model); // Adding Items in ComboBox
System.out.println(model);
}
}
catch(SQLException e){
System.out.println(e);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 501, 420);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 465, 146);
contentPane.add(panel);
panel.setLayout(null);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int n=comboBox.getSelectedIndex();
System.out.println(n);
System.out.println(comboBox.getSelectedItem());
textField.setText(?????); //Here What i need to code that selected models name should be place here.
}
});
comboBox.setBounds(109, 11, 86, 20);
panel.add(comboBox);
textField = new JTextField();
textField.setBounds(109, 47, 86, 20);
panel.add(textField);
textField.setColumns(10);
}
}
答案 0 :(得分:1)
代码将放在comboBox.addActionListener
。
//Connect database
String s = comboBox.getSelectedItem().toString();
String SQL = "SELECT * FROM `products` WHERE `Model` = '" + s + "'";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
requiredtextfield.setText(rs.getString("ColumnNAme_of_database"));
}
答案 1 :(得分:0)
您可以使用您将要使用的数据库中的所有必填字段引入购买类
public class Purchase {
int id;
String name;
String model;
...
public String toString() {
return model;
}
}
从DB创建购买实例中检索数据时,填充结果集中的字段。将购买项目放在组合框中。要提供正确的显示,您可以添加显示项目的模型字段的渲染器(更复杂),或者只是覆盖Purchase类的toString()方法以返回模型字段。
当在组合框中选择somethinf时,所选项目是特定的购买实例,您可以使用名称字段反映在文本字段中。