場景是,有組合框和2個文本框。 Combobox項目(模型)從數據庫中提取並動態更新Combobox。 我已經完成了。動態更新組合框中所選索引的數據庫值
現在我需要這樣做,當用戶從Combobox中選擇任何項目(模型),然後它的名字和價格應該在textfields中更新。
怎麼辦?
//這段代碼只有一個文本域,我將在之後創建。
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);
}
}
感謝您的幫助。請始終描述您的答案。還要保持使用準備好的語句以避免sql注入。 – hofmeister
謝謝我在@Junaid Ahmed的幫助下解決問題 –