因此,在Java
中,我有兩個類是使用swing components
創建的。在一個名爲SearchPage
的課程中,我在提供的Jtextfield
或Jcombobox
中設置了搜索參數,然後單擊apply jbutton
。當我這樣做時,根據包含數據的字段,我想將該變量發送到ItemPage
類,以便在我的pop_tree方法中使用該變量來搜索我的mysql數據庫並使用搜索結果填充樹。我怎樣才能做到這一點?在另一個類中使用jbutton動作將jcombobox變量從一個類傳遞到另一個類
下面是pop_tree
方法的代碼:
public final void pop_tree() throws SQLException {
//creating root node
DefaultTreeModel dbtree = (DefaultTreeModel)DBTree.getModel();
dbtree.reload();
dbtree.getRoot();
DefaultMutableTreeNode content = new DefaultMutableTreeNode("Content");
//let's see if I can create these child nodes
SearchPage s = new SearchPage();
try {
con = DBconnect.getConnection();
stm = con.createStatement();
s.apply_search_button.doClick();
if(s.apply_search_button.getModel().isPressed()){
//Grab what's in search field of Search Page
try{
String search = s.search_field.getText();
if (search == null){
return;
}else{
ResultSet rs = stm.executeQuery("SELECT * from displaydetails WHERE item LIKE '%"+search+"%'");
while (rs.next()){
DefaultMutableTreeNode itemNode = new DefaultMutableTreeNode (rs.getString("item"));
content.add(itemNode);
}
}
}catch(SQLException e){
System.out.println(e);
}
try{
//If a genre selection is made in the combo box:
if ((s.option_box.getSelectedItem())== "genre"){
String genre2 = s.result_box.getSelectedItem().toString();
if (genre2.equals(s.result_box.getSelectedItem())) {
ResultSet rs1 = stm.executeQuery("SELECT * from displaydetails WHERE genre = '" + genre2 + "';");
while (rs1.next()){
DefaultMutableTreeNode itemNode = new DefaultMutableTreeNode (rs1.getString("item"));
content.add(itemNode);
}
}
}
}catch(SQLException e){
System.out.println(e);
}
我已經創建設置搜索參數搜索表單,但是當我點擊apply_search_button
的形式,我想將變量發送到在pop_tree()
方法中執行搜索的適當位置。誰能幫我這個?謝謝。
你做到這一點,你從一個類傳遞任何信息到另一個同樣的方式,無論是通過方法參數或構造,這取決於你想要達到 – MadProgrammer
也許你什麼應該首先看看[將信息傳遞給方法或構造函數](https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html) – MadProgrammer
謝謝,但我知道如何做setter和獲得者。這種方法似乎並不奏效。另外,我想在我的mysql狀態中使用變量作爲參數進行搜索。 – VictorCreed