2013-03-20 86 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