Reputation: 55
I wrote this program that has a JComboBox with items that represent Tables in my database, each item is supposed to display it's content as they are in the database on a JTable when selected. I've run the program, but when I select the combo box items, only the first items in the comboBox display its contents on the JTable, subsequent selections aren't displaying anything. Could someone please take a look at it and tell me what am not doing right? or advice me on any useful tutorial? I will really appreciate ur help, thanks in advance!
public class InventoryItems extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private Object[] comboItems = new phoneClass().phoneManufacturerArray();
private JComboBox phoneBrandCombo = new JComboBox(comboItems);
private JPanel brandPane;
private JPanel instructionPane;
private JLabel instruction, brandLabel;
private JScrollPane scrollPane;
private JTable table;
private Object sel;
private Connection con;
private Statement stm;
private ResultSet rset;
private ResultSetMetaData meta;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
/**
* Add a Look&F to the GUI
*/
try{
UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
InventoryItems inst = new InventoryItems();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public InventoryItems() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
/**
* rows and column names declared as vectors.
*/
final Vector columnNames = new Vector();
final Vector data = new Vector();
sel = phoneBrandCombo.getSelectedItem();
//Get Selected Items and retrieve contents based on selected Item.
try{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException cnf){
System.out.println("Class Not Found Exception: "+cnf);
}catch(IllegalAccessException iaE){
System.out.println("Illegal Access Exception: "+iaE);
}catch(InstantiationException iE){
System.out.println("Instantiation Exception: "+iE);
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "phoneshopsystem", dbLogin.dbUser(), dbLogin.dbPwd());
String query = "SELECT phoneID, phoneModel, phonePrice, QuantityInStock FROM "+sel;
stm = con.createStatement();
rset = stm.executeQuery(query);
meta = rset.getMetaData();
int columns = meta.getColumnCount();
//Get Column Names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( meta.getColumnName(i) );
}
while (rset.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rset.getObject(i) );
}
//Fill JTable rows with database table rows
data.addElement( row );
}
rset.close();
stm.close();
con.close();
}catch(SQLException sql){
JOptionPane.showMessageDialog(null, "Table SQL Exception@: "+sql.getMessage());
}
/**
* Initialise the Table with the rows and column names
* retrieved from the database resultSet.
*/
table = new JTable(data, columnNames){
private static final long serialVersionUID = 1L;
public Class getColumnClass(int column){
for(int row = 0; row < getRowCount(); row++){
Object o = getValueAt(row, column);
if(o != null){
return o.getClass();
}
}
return Object.class;
}
};
/**
* Table properties
*/
{
//table.setPreferredSize(new java.awt.Dimension(534, 180));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setGridColor(Color.LIGHT_GRAY);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setSelectionBackground(new Color(248, 248, 248));
table.setSelectionForeground(new Color(51, 0, 51));
table.setBackground(new java.awt.Color(248,248,248));
}
// Add Table to JScrollPane
{
scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new java.awt.Dimension(534, 189));
scrollPane.setBackground(new java.awt.Color(212,208,200));
scrollPane.setBorder(BorderFactory.createTitledBorder(""));
scrollPane.setViewportView(table);
getContentPane().add(scrollPane, BorderLayout.SOUTH);
}
{
instructionPane = new JPanel();
FlowLayout instructionPaneLayout = new FlowLayout();
instructionPane.setLayout(instructionPaneLayout);
instruction = new JLabel();
instruction.setText("<html><body><br><p>"
+ "Select The Phone-Brand e.g 'Nokia',"
+ " To View Inventory."
+ "</p><br></body></html>");
instruction.setFont(new Font("Times New Roman", 3, 11));
instruction.setHorizontalAlignment(JLabel.CENTER);
instruction.setVerticalAlignment(JLabel.CENTER);
instruction.setBackground(new Color(240, 240, 240));
instruction.setEnabled(false);
instructionPane.add(instruction);
getContentPane().add(instruction, BorderLayout.NORTH);
}
{
brandPane = new JPanel();
FlowLayout brandPaneLayout = new FlowLayout();
brandPane.setLayout(brandPaneLayout);
brandLabel = new JLabel("Phone Brands: ");
brandLabel.setEnabled(false);
brandPane.add(brandLabel);
phoneBrandCombo.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == phoneBrandCombo.getSelectedItem()){
phoneBrandCombo.getSelectedItem();
}
}
});
brandPane.add(phoneBrandCombo);
brandPane.setBackground(new java.awt.Color(240,240,240));
getContentPane().add(brandPane, BorderLayout.CENTER);
}
pack();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setBackground(new java.awt.Color(240,240,240));
setPreferredSize(new Dimension(550, 330));
Upvotes: 0
Views: 2415
Reputation: 55
It Works alright with this:
phoneBrandCombo.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent ie){
if(ie.getStateChange() == ItemEvent.SELECTED){
selectedItem = ((JComboBox)ie.getSource()).getSelectedItem();
classes.loadTableData db = new classes.loadTableData();
db.loadData(selectedItem, data, columnNames);
table.setModel(new DefaultTableModel(data, columnNames));
}else{
data.removeAllElements();
columNames.removeAllElements();
}
} });
Upvotes: 0
Reputation: 10994
You load your data to Jtable
only once at constructing of that, and then you never do that, because of your Jtable
doesn't update while you select another item in JComboBox
.
Instead of using ActionListener
on your phoneBrandCombo
use ItemListener
like next:
phoneBrandCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent arg0) {
if(arg0.getStateChange() == ItemEvent.SELECTED){
Object object = ((JComboBox)arg0.getSource()).getSelectedItem();
//loadDataFromDBToTable(object);
}
}
});
here loadDataFromDBToTable(object);
is method for loading new data to your JTable
for selected object
.
Read about using JTable
and JComboBox
.
Upvotes: 1