How To Create And Add JMenuItem To JMenu Using MySQL And Java NetBeans
In this Java Tutorial we will see How To Create A JMenuItems Dynamically From MySQL Database By Geting Image And Text From Database And Set Them Into The Items In Java NetBeans .
Project Source Code:
// function to get the connection
public Connection getConnection()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/s_t_d", "root", "");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return con;
}
// function to add menuitem to menu
public void _addMenuItem(){
// create the connection from getConnection function
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
// execute select query
rs = st.executeQuery("SELECT * FROM mypics");
while(rs.next()){
// get the image from database
// resize the image
// create the jmenuitem with name and image from mysql
ImageIcon img1 = new ImageIcon(rs.getBytes("pic"));
Image img2 = img1.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);
ImageIcon img3 = new ImageIcon(img2);
JMenuItem jmi = new JMenuItem(rs.getString("name"),img3);
jmi.setIcon(img3);
// add the jmenuitem to the jmenu
jMenu1.add(jmi);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}