I am stuck here and see only one solution which I am trying to refrain from because, it will make my code look messy. I have a JComboBox.addPopupMenuListener in one class. I have another class which implements addPopupMenuListener. In the other class, I extract the items from DB and store them in a List.
I am completely clueless now on how do I add items from this List to JComboBox. Any ideas?
Problem - although I have declared JComboBox combobox; as public I am unable to use this combobox in the implementing class. What do I do? Below is the Code -
package tg.com.bugtracker.loginpage;
import java.awt.*;
import javax.swing.*;
public class LoginPanel extends JPanel {
public JComboBox<String> combobox;
public LoginPanel() {
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.insets = new Insets(10,10,10,10);
constraints.anchor = GridBagConstraints.LINE_START;
combobox = new JComboBox<>();
combobox.setPreferredSize(new Dimension(250, 20));
combobox.addPopupMenuListener(new loginNames());
add(combobox, constraints);
}
}
Implementing Class -
package tg.com.bugtracker.loginpage;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.sql.*;
import java.util.List;
public class loginNames implements PopupMenuListener{
@Override
public void popupMenuCanceled(PopupMenuEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
// TODO Auto-generated method stub
}
public List<String> loginNames;
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\BugTrackerDB.accdb";
ResultSet rs;
PreparedStatement p;
String sqlquery = "SELECT FirstName FROM UserDetails;";
try {
Connection cnn = DriverManager.getConnection(URL);
p = cnn.prepareStatement(sqlquery);
rs = p.executeQuery();
rs.close();
p.close();
while (rs.next()) {
String names = rs.getString("FirstName");
loginNames.add(names);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}