Search code examples
hivejtextfieldjlistselecteditem

How to get selected element text from jlist with image icon?


Error Image Using Object I'm trying to display the selected element text in a jtextfield from jlist. The list contains database data and image, where getting selected value from list following error throws.

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: hive.test.ImgsNText cannot be cast to java.lang.String

My code

String index = String.valueOf(jList1.getSelectedIndex());
jTextField1.setText(index);
String s = (String) jList1.getSelectedValue();
jTextField2.setText(s);

Getting database data and displaying in jlist-code

try {
        Class.forName("org.apache.hive.jdbc.HiveDriver");
        Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "arunachalam", "");
        Statement st = con.createStatement();
        String sql = "show databases";
        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            String s1 = rs.getString(1);
            dm.addElement(new ImgsNText(s1, new ImageIcon("images/hive_db.png")));
        }
        jList1.setCellRenderer(new Renderer());
        jList1.setModel(dm);
        if(jList1.isSelectedIndex(0))
        {

        }
    } catch (Exception e) {
        showMessageDialog(null, "Exception");
    }

Suggest me how to get the text alone from jlist and displaying it in jtextfield.


Solution

  • First you have to create a ListCellRenderer that is used to show the image and text both in List. and then call a ListSelectionListener on list that capture event of click on list selection.Then get the selected item and set the text of selected item in Text field.

    UPDATED CODE

    import java.awt.Component;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import javax.swing.DefaultListModel;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JTextField;
    import javax.swing.ListCellRenderer;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    public class ListExample implements ListSelectionListener {
    
      JList list;
      DefaultListModel listModel;
      JTextField txtField;
      Connection connection;
      PreparedStatement pst;
      ResultSet rs;
    
      public ListExample() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("LIST");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        Container con = frame.getContentPane();
    
        ListRenderar rendrar = new ListRenderar();
        list = new JList();
        txtField = new JTextField(10);
    
        listModel = new DefaultListModel();
        try {
          Class.forName("com.mysql.jdbc.Driver");
          connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ganesh", "root",
              "admina");
          pst = connection.prepareStatement("show databases");
          rs = pst.executeQuery();
          while (rs.next()) {
            String text = rs.getString(1);
            listModel.addElement(new ImgNText(text, new ImageIcon("/images/help.gif")));
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        list.setModel(listModel);
    
        list.setCellRenderer(rendrar);
        list.addListSelectionListener(this);
    
        con.add(list);
        con.add(txtField);
    
        con.setLayout(new FlowLayout());
    
        frame.setVisible(true);
        frame.pack();
      }
    
      public class ListRenderar extends JLabel implements ListCellRenderer {
    
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
    
          ImgNText imgNtext = (ImgNText) value;
          ImageIcon icon = imgNtext.getImage();
          String name = imgNtext.getText();
    
          setIcon(icon);
          setText(name);
    
          return this;
        }
      }
    
      public void valueChanged(ListSelectionEvent e) {
        ImgNText obj = (ImgNText) list.getSelectedValue();
        txtField.setText(obj.getText());
      }
    
      public class ImgNText {
    
        ImageIcon image;
        String text;
    
        public ImgNText(String text, ImageIcon image) {
          this.image = image;
          this.text = text;
        }
    
        public ImageIcon getImage() {
          return image;
        }
    
        public String getText() {
          return text;
        }
      }
    
      public static void main(String args[]) {
        new ListExample();
      }
    }