2013-03-20 26 views
0

我是初學者,我試圖找出辦法有當一個新條目被插入到MySQL數據庫列一個JButton自動創建。該按鈕的文本將從數據庫中的條目中拉入。我已經想出瞭如何從表格中提取信息作爲jbutton文本,但是,我覺得必須有一種更簡單的方法來實現它。任何這些問題的想法?我在下面包含了我的代碼片段。謝謝!創建JButton的使用MySQL數據庫條目

public class JuniorSkills extends javax.swing.JFrame { 

/** 
* Creates new form JuniorSkills 
*/ 
public JuniorSkills() throws ClassNotFoundException { 
initComponents(); 
    Connection conn = null; 
    Statement statement = null; 
    ResultSet rs = null; 


    try { 
     Class.forName("com.mysql.jdbc.Driver"); 
     conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password"); 
     System.out.println("Connected to database"); 

     statement = conn.createStatement(); 
     rs = statement.executeQuery("SELECT * FROM skill_table WHERE class='junior'"); 

     int count = 0; 
     while(rs.next()) 
     { 
      count++; 
      String gotit = rs.getString(1); 
      //System.out.println(gotit); 
      if(count==1) 
      { 
       Skill1.setText(rs.getString(1)); 
      } 
      else if(count==2) 
      { 
       skill2.setText(rs.getString(1)); 
      } 
      else if(count==3) 
      { 
       skill3.setText(rs.getString(1)); 
      } 
      else if(count==4) 
      { 
       skill4.setText(rs.getString(1)); 
      } 
      else if(count==5) 
      { 
       Skill5.setText(rs.getString(1)); 
      } 
      else if(count==6) 
      { 
       skill6.setText(rs.getString(1)); 
      } 
      else if(count==7) 
      { 
       Skill7.setText(rs.getString(1)); 
      } 
      else if(count==8) 
      { 
       Skill8.setText(rs.getString(1)); 
      } 
      else if(count==9) 
      { 
       Skill9.setText(rs.getString(1)); 
      } 
      else if(count==10) 
      { 
       Skill10.setText(rs.getString(1)); 
      } 
     } 
    } catch (SQLException ex) { 
     Logger.getLogger(JuniorSkills.class.getName()).log(Level.SEVERE, null, ex); 
    } 



} 
+1

如果你有一個固定數量的按鈕,創建一個按鈕陣列 – MadProgrammer 2013-03-20 00:01:59

+0

不要破壞你自己的問題!編輯回滾。 – 2013-03-20 01:15:31

回答

1

如果你永遠只能有行的固定號碼,你可以或者創建JButton小號

private JButton[] myFixedListOfButtons; 

//...// 

myFixedListOfButtons = new JButton[10]; 

//...// 

while(rs.next()) 
{ 
    String gotit = rs.getString(1); 
    if (count < myFixedListOfButtons.length) 
    { 
     myFixedListOfButtons[count].setText(gotit); 
    } 
    count++; 
} 

一個數組,如果你有一個可變的行數,你應該簡單地創建按鈕因爲你需要

removeAll(); // remove all the old buttons... 
while(rs.next()) 
{ 
    String gotit = rs.getString(1); 
    JButton btn = new JButton(gotit); 
    add(btn); 
} 
+0

謝謝你們兩位。我會試一試,看看我能想出什麼。 – user2188777 2013-03-20 00:15:00