Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an app that allows the user to choose 2 options from 2 comboboxes, and then info from the database is outputted to a jtable. Recently, as an experiment I created two custom combo boxes, I made a separate package, and a class just for the custom combo boxes to see if it would work. It worked. The next step is to get that custom combo box to replace the generic swing combo box from my current app(where I just drag and dropped a combo box onto the swing interface on netbeans.

This is the custom combo box:


Java
public class CustomComboBoxDemo extends JPanel {
    ImageIcon[] images;
    String[] colorStrings = {"    White", "Off-White", "    Peach", "     Gray",
        "       Tan", "       Pink", "     Green", "        Red", "    Yellow",
    "    Purple", "  Orange","   Brown", "    Black", "    Clear" };

 
    public CustomComboBoxDemo() {
        super(new BorderLayout());

       
        images = new ImageIcon[colorStrings.length];
        Integer[] intArray = new Integer[colorStrings.length];
        for (int i = 0; i < colorStrings.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = createImageIcon(colorStrings[i] + ".png");
            if (images[i] != null) {
                images[i].setDescription(colorStrings[i]);
            }
        }

        
        JComboBox colorList = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        renderer.setPreferredSize(new Dimension(120, 100));
        colorList.setRenderer(renderer);
        colorList.setMaximumRowCount(7);

        
        add(colorList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }

    
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = CustomComboBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
                return null;
        }
    }

  
    private static void createAndShowGUI() {
        
        JFrame.setDefaultLookAndFeelDecorated(true);

        
        JFrame frame = new JFrame("CustomComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       
        JComponent newContentPane = new CustomComboBoxDemo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

       
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    class ComboBoxRenderer extends JLabel
                           implements ListCellRenderer {
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }

     
        public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
            
            int selectedIndex = ((Integer)value).intValue();

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            
            ImageIcon icon = images[selectedIndex];
            String color = colorStrings[selectedIndex];
            setIcon(icon);
            if (icon != null) {
                setText(color);
                setFont(list.getFont());
            } else {
                setUhOhText(pet + " (no image available)",
                            list.getFont());
            }

            return this;
        }

       
        protected void setUhOhText(String uhOhText, Font normalFont) {
            if (uhOhFont == null) { 
                uhOhFont = normalFont.deriveFont(Font.ITALIC);
            }
            setFont(uhOhFont);
            setText(uhOhText);
        }
    }
}




and this is the code from the app which is working and where I would like to replace the current combo boxes, with the custom combo boxes from the previous code.


Java
public class NewJFrame extends javax.swing.JFrame {
    
  
    public NewJFrame() {
        initComponents();
       
   
    }


    
   
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      DefaultTableModel model = new DefaultTableModel();
                
                
                
       
           String sqlQuery = "select COLUMN1, COLUMN2, COLUMN3, COLUMN4, COLUMN5, COLUMN6 from APP.DATA123 "
+ "where (COLUMN1 = ?) AND (COLUMN2 = ?) AND (COLUMN3 = ?) OR (COLUMN2 = ?) AND (COLUMN3 = ?)";

                         

            String abc = jTextField2.getText();
            String cba = (String)jComboBox1.getSelectedItem();
            String cab = (String)jComboBox2.getSelectedItem();
            String data = "jdbc:derby://localhost:1527/sample";
        try (
              Connection conn = DriverManager.getConnection(
              data, "app", "app");
              PreparedStatement st = conn.prepareStatement(sqlQuery))   { 
            
          
          
          Class.forName("org.apache.derby.jdbc.ClientDriver");
          st.setString(1, abc);
          st.setString(2, cba);
          st.setString(3, cab);       
          st.setString(4, cba);
          st.setString(5, cab);
          ResultSet rec = st.executeQuery();
          jTable1.getColumnModel().getColumn(6).setCellRenderer(new ImageRenderer());
          jTable1.setModel(DbUtils.resultSetToTableModel(rec));
       
               st.close(); 
 
    
            } catch (SQLException s)  {
          System.out.println("SQL Error: " + s.toString()  + " "
                  + s.getErrorCode() + " " + s.getSQLState());
      } catch (Exception e) {


}
}
          System.out.println("Error: " + e.toString()
          + e.getMessage());    public static void main(String args[]) {
      
           

      
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JComboBox<String> jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField2;
                    
}



I tried a few different ways, none of which worked. What is simplest way to add this combo box to the app?

Also, as a side question, in netbeans, usually there is a projects tab, a files tab, and a services tab to the left side. I am not sure what I did, but now I only have a files tab, and don't have the other tabs, one of which contained my database……. can I get those back?? :(

What I have tried:

I have tried calling creating a new class within the code.
Posted
Updated 11-Oct-16 0:30am
v3
Comments
Suvendu Shekhar Giri 11-Oct-16 9:22am    
Does that give any error?
Member 12767173 11-Oct-16 17:02pm    
When I run the custom combo box in its own package/class, it works great, same with when I run the app using the generic comboboxes from dragging and dropping a combobox into the swing design. I just am not sure how to incorporate the combobox into that app, and remove the generic comboboxes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900