Population of  JList

How can I populate a JList with the file name in a directory, do later on the files can be passed to another program for execution?

have you looked at the JList API docs, there's a How to use Lists link in the top to a good tutorial that should be enough to figure it out.

Similar Messages

  • Populating Swing JList using SQL Database

    Sup peeps, im trying to to populate a JList using the entries in a table in a database i created.
    package networks;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.PrintWriter;
    import java.sql.*;
    public class Contestantlist extends javax.swing.JFrame {
        /** Creates new form contestantList */
        public Contestantlist() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
             try
               // Load driver's class, inilialize, register with DriverManager
               //Class.forName("oracle.jdbc.driver.OracleDriver");
               Class.forName("org.gjt.mm.mysql.Driver");
            catch (ClassNotFoundException e)
               System.out.println("Unable to load driver class");
               return;
            ResultSet rs = null;
            try
               // Call DriverManager's methods (all are static)
               // To print log on sysout
               //DriverManager.setLogStream(System.out); //JDBC 1.x driver
              // DriverManager.setLogWriter(new PrintWriter(System.out) );
               // Connect to database.  DriverManager loads each registered driver
               // in turn until one can handle the database URL format
               //Connection con = DriverManager.getConnection(
               //                     "jdbc:oracle:thin:@host.domain.com:1521:db_name"
               //                     ,"scott","tiger");
              // Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               // Get the DatabaseMetaData object to display database info
            //   DatabaseMetaData dmd = con.getMetaData();
             //  Statement stmt = con.createStatement();
           //     String sql;
             //  sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
              // rs = stmt.executeQuery(sql); //throws SQLExecption if fails
              // printResultSet(rs);
               DriverManager.setLogWriter(new PrintWriter(System.out) );
               Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               // Get the DatabaseMetaData object to display database info
               DatabaseMetaData dmd = con.getMetaData();
               String sql;
                 Statement stmt = con.createStatement();
             sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
             rs = stmt.executeQuery(sql); //throws SQLExecption if fails
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCols = rsmd.getColumnCount();*
            // Display data, fetching until end of the result set
            // Calling next moves to first or next row and returns true if success
            while(rs.next() )
               // Each rs after next() contains next rows data
               for(final int i=1; i<=numCols; i++)
                  if(i > 1) System.out.print(",");
                  // Almost all SQL types can be cast to a string by JDBC
                 // System.out.print(rs.getString(i));
                  theList.setModel(new javax.swing.AbstractListModel() {
                      String[] strings = { rs.getString(i) };
                      public int getSize() { return strings.length; }
                      public Object getElementAt(int i) { return rs.getString(i); }
               System.out.println("");
            catch(Exception f)
            titleLabel = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
           // theList.setVisibleRowCount(6);
            theList = new javax.swing.JList();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
            titleLabel.setText("The Scrupulous Contestants!");
           /* theList.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 3", "Item 4", "Item 5", "Item 4", "Item 5"  };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    jScrollPane1.setViewportView(theList);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(70, 70, 70)
    .addComponent(titleLabel))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(71, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(titleLabel)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(124, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    /* private static void printResultSet(ResultSet rs) throws SQLException
         DriverManager.setLogWriter(new PrintWriter(System.out) );
    Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
    // Get the DatabaseMetaData object to display database info
    DatabaseMetaData dmd = con.getMetaData();
    String sql;
         Statement stmt = con.createStatement();
    sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
    rs = stmt.executeQuery(sql); //throws SQLExecption if fails
    ResultSetMetaData rsmd = rs.getMetaData();
    int numCols = rsmd.getColumnCount();
    // Display data, fetching until end of the result set
    // Calling next moves to first or next row and returns true if success
    while(rs.next() )
    // Each rs after next() contains next rows data
    for(int i=1; i<=numCols; i++)
    if(i > 1) System.out.print(",");
    // Almost all SQL types can be cast to a string by JDBC
    System.out.print(rs.getString(i));
    System.out.println("");
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Contestantlist().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JList theList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration
    I can tell that im not using something correctly. Can you guys just point out how i should proceed through this? I encapsulated the piece of code that has got me confused.
    Edited by: 860597 on May 29, 2011 6:29 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    package networks;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.PrintWriter;
    import java.sql.*;
    public class Contestantlist extends javax.swing.JFrame {
        public Contestantlist() {
            initComponents();
        @SuppressWarnings("unchecked")
        private void initComponents() {
             try
               Class.forName("org.gjt.mm.mysql.Driver");
            catch (ClassNotFoundException e)
               System.out.println("Unable to load driver class");
               return;
            try
                 ResultSet rs = null;
               DriverManager.setLogWriter(new PrintWriter(System.out) );
               Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               DatabaseMetaData dmd = con.getMetaData();
               String sql;
                 Statement stmt = con.createStatement();
             sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
             rs = stmt.executeQuery(sql);
             printResultSet(rs);
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCols = rsmd.getColumnCount();
            catch(Exception f)
            titleLabel = new javax.swing.JLabel();
            jScrollPane2 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
            titleLabel.setText("The Scrupulous Contestants!");
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane2.setViewportView(jTable1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, 0)
                            .addComponent(titleLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, 0)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(33, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(titleLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(263, Short.MAX_VALUE))
            pack();
        }// </editor-fold>/ </editor-fold>
        private static void printResultSet(ResultSet rs) throws SQLException
               DriverManager.setLogWriter(new PrintWriter(System.out) );
              Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
              DatabaseMetaData dmd = con.getMetaData();
              String sql;
                Statement stmt = con.createStatement();
            sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
            rs = stmt.executeQuery(sql); //throws SQLExecption if fails
           ResultSetMetaData rsmd = rs.getMetaData();
           int numCols = rsmd.getColumnCount();
           while(rs.next() )
              for(int i=1; i<=numCols; i++)
                 if(i > 1) System.out.print(",");
                 System.out.print(rs.getString(i));
              System.out.println("");
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Contestantlist().setVisible(true);
        private javax.swing.JList theList;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel titleLabel;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JTable jTable1;
    }I have amended the code and now it does print out the specified contents of my table.
    I have added a a JTable, but excuse my ignorance because i have no idea as to how to proceed from here. I can't figure out how call database entries from the array in the JTable.
    Edited by: 860597 on May 29, 2011 7:27 AM

  • What would be best way of populating a JList?

    Hi all,
    I'm trying to put a list of users in a program so that one can be selected, I need to display the users name but also need to associate a user ID number with that field on that list that can't be seen.
    The tutorials i've found only allow me to add the username and then when selected i can only retrieve index number that user is listed at. Would there be a way of storing the user ID as well in the list or should i use an array or something to store the IDs?
    Thanks

    http://forum.java.sun.com/thread.jspa?threadID=636201

  • Probably NetBeans but: jList RE-populating

    This probably is a NetBeans question but maybe you all can help:
    I am having difficulty with NetBeans populating a jList anytime after it is initially populated/initialized by the GUI.
    Here is code I wrote and added to NetBeans "Post-Adding" code that works fine the first time (and it is way for us humans to interact with the GUI's generated code):
    jScrollPane1.setViewportView(jList1);
    listModel = new DefaultListModel();
    List<String> GUI_ReadFile_ls=new ArrayList<String>();
    GUI_ReadFile_ls=RF_Call.ls;
    Iterator it=GUI_ReadFile_ls.iterator();
    while(it.hasNext())
    String value=(String)it.next();
    listModel.addElement(value);
    //System.out.println("LIST Value from GUI :"+value);
    jList1 .setModel(listModel);
    That code works fine and populates the list.
    (RF_Call is my ReadFile class which reads an ascii text file that is used here to populate the jList).
    But I added a button and I want it to read another file and re-populate the same jList.
    My button-press code is
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String sTheFile=new String("C:/MyDir/Docs/MyCarData.txt");
    RF_Call.LoadFile(sTheFile);
    But the jList doesn't get populated.
    How do you populate a jList after it has already been populated - and how do you get that displayed?
    Thanks,
    Matt

    jList1.setModel(new javax.swing.AbstractListModel() {
    String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
    public int getSize() { return strings.length; }
    public Object getElementAt(int i) { return strings; }
    jScrollPane1.setViewportView(jList1);
    listModel = new DefaultListModel();
    List<String> GUI_ReadFile_ls=new ArrayList<String>();
    GUI_ReadFile_ls=RF_Call.ls;
    Iterator it=GUI_ReadFile_ls.iterator();
    while(it.hasNext())
    String value=(String)it.next();
    listModel.addElement(value);
    //System.out.println("LIST Value from GUI :"+value);
    jList1 .setModel(listModel);
    Oh, man the code markers didn't work that time either.
    Now Kevin will really be pissed.
    I'll post that as a separate question as well.
    Matt                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Delays in JList updates

    I would like to let users know the application is still "working" when a JList is being populated.
    Typically, I set an hourglass cursor, do some work, fill in the list, then go back to the default cursor. If I used a progress monitor and a thread, I think I would have the same problems.
    1. Set cursor to wait
    2. Go get data from DB, add items to JList
    3. Set cursor to default.
    The problem is, the wait cursor goes away when I am done populating the JList, but there is a long delay before the data is actually displayed. This happens regardless of the data model I use, either adding items one at a time, or dumping a vector into the model.
    I would prefer the wait cursor to be displayed until the data is displayed, so the user knows things are still going on.
    Any ideas as to why this happens, or how to enhance it?
    thanks,

    In experimenting, I added a paintImmediately() call inbetween steps 2 and 3. This held the wait cursor on until the data was displayed.

  • Best Practice for fireIntervalAdded, Removed

    Having a hard time finding much information on the proper use if fireIntervalAdded and fireIntervalRemoved. For example, if I wanted to clear a JList's ListModel and repopulate it from scratch, what would be the proper calls to these two methods?
    int size = getSize();
    this.clear();
    fireIntervalRemoved(this, 0, size-1);
    repopulateList();
    fireIntervalAdded(this, 0, getSize()-1);
    Thanks.

    Those model methods do call the fire methods, that's
    how the model tells the view to what to refresh. The
    fire methods create events for the ListDataListener
    interface that JList implements. I presume that the
    OP was talking about creating his own
    AbstractListModel implementation.I understand that those methods do call the fire. . . methods. My point was that he didn't have to call them explicitly if he used the DefaultListModel. To me the OP was asking the simpler question about clearing and re-populating his JList: I may be wrong.
    Cheers
    DB

  • Populating JList with a single database column

    Hi all,
    I have the following code and i'm trying to popluate the JList with a particular colum from my MySQL Database..
    how do i go about doing it??
    Can some one please help
    import java.awt.*; import java.awt.event.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class RemoveD extends JDialog {     private JList list;     private JButton removeButton;     private JScrollPane scrollPane;     private Connection conn = null;     private Statement stat = null;         public RemoveD(Frame parent, boolean modal) {         super(parent, modal);         initComponents();     }     private void initComponents() {         scrollPane = new JScrollPane();         list = new JList();         removeButton = new JButton();         setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);         getContentPane().setLayout(new GridLayout(2, 0));         scrollPane.setViewportView(list);         getContentPane().add(scrollPane);         removeButton.setText("Remove");         removeButton.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent evt) {                 removeButtonActionPerformed(evt);             }         });         getContentPane().add(removeButton);         pack();         try {             Class.forName("com.mysql.jdbc.Driver");                    } catch (ClassNotFoundException ex) {             ex.printStackTrace();                    }         try {             String userID = "";             String psw = "";             String url;             url = "jdbc:mysql://localhost:3306/names";             conn = DriverManager.getConnection(url, userID, psw);             stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,                     ResultSet.CONCUR_READ_ONLY);             stat.close();             conn.close();         } catch (SQLException ex) {             ex.printStackTrace();         }     }     private void removeButtonActionPerformed(ActionEvent evt) {     }     public static void main(String args[]) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 RemoveD dialog = new RemoveD(new JFrame(), true);                 dialog.addWindowListener(new WindowAdapter() {                     public void windowClosing(WindowEvent e) {                         System.exit(0);                     }                 });                 dialog.setVisible(true);             }         });     } }

    I figured out how to do it

  • Populating JList

    I want to dinamically populate a JList (lstDetalhes) on start up.
    I'm using a method to do it; this method needs to read a selected value from another JList (lstTurmas) that is also loaded at startup.
    here's the method:
        javax.swing.DefaultListModel lm;
        public javax.swing.DefaultListModel q10Escolhidos() throws Exception {
            System.out.println("in?cio");
            javax.swing.DefaultListModel lm = new javax.swing.DefaultListModel();
            Configuration cfg = null;
            try {
                cfg = new Configuration()
                      .addClass(Turma.class)
                      .addClass(Relatorio.class)
                      .addClass(Disciplina.class)
                      .addClass(Detalhe.class);
            catch (MappingException ex) {
            SessionFactory sf = null;
            try {
                sf = cfg.buildSessionFactory();
            catch (HibernateException ex1) {
            Session sess = null;
            try {
                sess = sf.openSession();
            catch (HibernateException ex2) {
            Transaction t = null;
            try {
                t = sess.beginTransaction();
            catch (HibernateException ex3) {
            String s = (String) visual.lstTurmas.getSelectedValue();
            System.out.println("o que est? seleccionado na lista das turmas: " + s); // that's where prints NULL
            LeLista ll = new LeLista();
            //int oano = ll.oAno(s);
            //System.out.println("O ano ? :" + oano);
            int oano=4;//++++++ tinha de throws exception
            //String aturma = ll.aTurma(s);
            //System.out.println("A truma  ? :" + aturma);
            String aturma ="A";
            aturma = "" + "'" + aturma + "'";
            String query =
                "select rel from Relatorio as rel where rel.turma.ano = " + oano +
                " AND turma = " + aturma;
            List lista = null;
            try {
                lista = sess.find(query);
            catch (HibernateException ex4) {
            rel = (Relatorio) lista.get(0);        
            lm.addElement(rel.getTurma().getDetalhe());
            return lm;
    }Inside this method i call leLista:
    public class LeLista {
        public LeLista() {
        //obter a turma
        public String aTurma(String s) {
            String a = s.substring(3);
            //System.out.println("a turma: " + a.trim());
            a = a.trim();
            return a;
        //obter o ano
        public int oAno(String s) {
            String a = s.substring(0, 1);
            a = a.trim();
            int b = Integer.parseInt(a);
            //System.out.println("o ano " + b);
            return b;
    }Basically i'm using two classes: Assistente.java - the brain of my app - (from which the above method belongs) and VisualSwing.java - where visual components are created, etc.
    As i had trouble initializing my JList's listModel, i created this mehtod that is written inside VisualSwing.java:
        Assistente assistente = new Assistente(this);
        public javax.swing.DefaultListModel q10Escolhidos() {
            try {
                info2 = assistente.q10Escolhidos();
            catch (Exception ex) {
                System.out.println("Erro de q10Escolhidos");
            return info2;
        DefaultListModel info2 = new DefaultListModel();Now - to my problem: if i try it just like the code above - manually saying which ANO and TURMA i wanted the REL loaded, its ok;
    What happens is that i dont want it like that - i want it dinamically generated.
    I wrote some print msg:
    System.out.println("o que est? seleccionado na lista das turmas: " + s);
    but says...null
    This means that when this method goes searching for the selected value in lstTurmas, its not yet loaded, so gives... null.
    How can i solve this?
    thanks a lot in advance

    case solved!
    i split the listmodel generator method in two: one creates the listmodel, while the second later adds whatever i want to it

  • Populating JList with JDBC

    Hello
    I want to transfer my selected content from A list to B list and the content in the A list is set using JDBC. i am very new to it.please help me.i have tried writing it but not getting the list on the frame. also please let me know when to use list cell renderer? really getting confused in this.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.net.*;
    public class msgwin extends JFrame extends MouseListener
      JFrame jf;
      DefaultListModel defau1,defau2;
      JList slist,dlist;
      JLabel slabel,dlabel;
      JButton addb,removb;
      String name;
      msgwin()
       jf=new JFrame("Grape Chat v1.2 beta");
       jf.setBounds(40,30,500,400);
       jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       JFrame.setDefaultLookAndFeelDecorated(true);
       jf.setLayout(null);
       jf.setResizable(false);
       try
        Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("dbc:oracle:thin:@192.168.1.2:1521:orcl","SCOTT","iamakhila");
         Statement st=con.createStatement();
         ResultSet rs=st.executeQuery("select fname from data");
         defau=new DefaultListModel();
         while(rs.next())
          name=rs.getString(1);
          System.out.println(name);
          defau.addElement(name);
       slist=new JList(defau);
       slist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       slist.setSelectedIndex(0);
       slist.addListSelectionListener(this);
       slist.setVisibleRowCount(10);
       JScrollPane listScrollPane = new JScrollPane(slist);
       st.close();
       con.close();
      }catch(Exception e){}
      public void mouseClicked(MouseEvent e)
       slist=(JList)e.getSource();
       //int index=slist.locationToIndex(e.getPoint);
       defau2=new DefaultListMode();
       dlist=new JList(defau2);
       if(e.getClickCount()==2)
         defau2.addElement(slist.getSelectedIndex());
      public void mouseEntered(MouseEvent e){}
      public void mouseExited(MouseEvent e){}
      public void mousePressed(MouseEvent e){}
      public void mouseReleased(MouseEvent e){}
      public static void main(String args[])
        msgwin ms=new msgwin();
    Thanking in advance.
    kindly guide me

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

  • Can't select when JList populated by LOV

    I'm at a loss here...
    JDev 10.1.2.1 (1913)
    I'm creating a simple Swing Shuttle panel. I want standard action, i.e. when the 'shuttle' button is pressed, the selected items in JList1 move to JList2.
    I first created this with JList1 bound to a VO. I quickly realized that I couldn't remove elements from the list without removing the appropriate rows from VO...tried to do that but ran into errors.
    Ok, so i figured I'd create a programmatic VO and followed the documentation to populate this with a LOV from the db-backed VO attribute I want.
    The problem is that all list values are grayed out and un-selectable
    Steps:
    1 - Create DB-backed VO and programmatic-backed VO with same attributes (I created these using the Ename field from Scott.EMP)
    2 - Create JPanel
    3 - Find the programmatic-backed VO on the Data Control palette
    4 - Expand to find the attribute I want to show in my JList; select "Drag and drop as List"; drag onto my panel
    5 - Open the List binding editor from the Structure window
    6 - On the LOV Update attributes tab I select the DB-backed VO as the source and the programmatic VO as the target
    7 - On the LOV display attributes tab I shuttle over the attribute I want to display (Ename)
    I tried the three different selectionModes...I compared the properties of the VO-backed JList with the LOV-backed list and can't find a difference. I fooled around with the "Updatable" settings in the VO...
    Any ideas why this doesn't work as i expect?
    thanks
    John

    I'm not sure that there is anything in the ADF Bindings to help you here. What we have done is to programatically execute the query and add each Row to the JList. You will need a custom renderer to the JList so that the list knows which attribute from the Row to display. Then when you shuttle the row over, you just remove it from the first JList and add it to the 2nd JList. It is also very easy to create a generic ListCellRenderer that knows how to display Row objects. Here is one that we use:
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import oracle.jbo.Row;
    public class ADFRowListCellRenderer extends JLabel implements ListCellRenderer {
      private String attributeName = null;
      public ADFRowListCellRenderer(String attributeToDisplay) {
        this.attributeName = attributeToDisplay;   
      public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {  
        Row row = (Row) value;
        String fieldValue = null;
        if( row != null ) {
          Object objectValue = row.getAttribute(attributeName);  
          if( objectValue != null ) {
            fieldValue = objectValue.toString();  
        setText(fieldValue == null ? "" : fieldValue);
        setOpaque(true);
        setBackground(isSelected
               ? list.getSelectionBackground()
               : list.getBackground());
        setForeground(isSelected
               ? list.getSelectionForeground()
               : list.getForeground());    
        return this;
    }One thing to remember is that a Row instance has some internal id assigned to it, so if you re-execute the query, your list's Row references will be invalid. If you have to re-execute the query, then you will need to clear the JLists and reload the Rows.
    Hope this helps
    Erik

  • Jlist not displaying correctly when populated by thread

    Hi, I have this problem when a thread attempts to populat a Jlist, it will only populate sometimes. Othertimes, it doesnt display correctly. The model will have the correct objects in it, but the display on screen will not appear. I have some code below that demonstrates the problem. I renger html in the Jlist just so that its easier to see, but doesnt have to be html.
    import javax.swing.*;
    public class listtest extends javax.swing.JFrame {
    private DefaultListModel model = new DefaultListModel();
    public listtest() {
    initComponents();
    jList1.setModel(model);
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jList1 = new javax.swing.JList();
    jButton1 = new javax.swing.JButton();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jScrollPane1.setViewportView(jList1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    getContentPane().add(jButton1, java.awt.BorderLayout.SOUTH);
    pack();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    new myThread().start();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new listtest().show();
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
    class myThread extends Thread{
    public void run(){
    model.clear();
    String temp;
    for(int i = 0; i < 100; ++i){
    temp = "<html><table><tr><td>" + i + "</td></tr></table></html>";
    model.addElement(temp);
    When you push the button, sometimes the list will come out correctly and sometimes it wont. Anyone know how to get it to display correctly? I tries all sort of things with InvokeLater, validates, repaints, etc. I cant get anything to get it to display properly.

    I think this is closer to what you wanted.
    Your sample code if obviously simple enough not to need it, but this allows you to thread off the work and the use invokeLater only to push the results back to the UI/event thread.
    for( int i = 0; i < 100; ++i )
    final String temp = "<html><table><tr><td>" + i + "</td></tr></table></html>";
    SwingUtilities.invokeLater(
    new Runnable()
        public void run()
            model.addElement(temp);
    }

  • JList populating

    I have a JList of English Counties which when selected removes that county from that JList and puts it into another JList. The problem I getting is that all the content from the JList I'm selecting tends to disappear almost at random.
    I think the problem lies with a timer I'm running on the JList ListSelectionListener whose intention is to slow the click rate down as it was capturing more information than I was intending when clicking. I've tried to map the program flow with System.out comments but it appears that it actually calls the populate method.
    I'll give my code (it needs a tidy up, but I'm getting to that). I'll appreciate any suggestions on this, I'm sure there are cleaner ways to populate one JList from another:
      /* populates the areaList (JList) from the given arrayList */
       private void populateAreaList(){
         dlm=(DefaultListModel)areaList.getModel();
         dlm.clear();
         englishCounties=orderList(englishCounties);
         Iterator iter=getEnglishCounties().iterator();
         while(iter.hasNext()){
           String area=(String)iter.next();
           dlm.addElement(area);
      /* populates the selectedAreaList JList from the given arrayList */
       private void populateselectedArea(){
         dlm=(DefaultListModel)selectedAreaList.getModel();
         dlm.clear();
         selectedArea=orderList(selectedArea);
         Iterator iter=selectedArea.iterator();
         while(iter.hasNext()){
           dlm.addElement((String)iter.next());
       private static java.util.Timer countyTimer;
       /* Listener added to the areaList JList called when item is selected*/
       class CountyListener implements ListSelectionListener{
         int insideCount=0;
         int minIndex;
         boolean isCanAdd=true; // flag to see whether next click can be captured.
         public void valueChanged(ListSelectionEvent e){
            insideCount++;
            if(insideCount % 2==0){
              ListSelectionModel lsm=(ListSelectionModel)e.getSource();
              if(lsm.isSelectionEmpty()){
             System.out.println("No Selection");
              else{
                  minIndex=lsm.getMinSelectionIndex();
                  if(lsm.isSelectedIndex(minIndex)){
                      if(isCanAdd){
                         isCanAdd=false;
                         countyTimer=new java.util.Timer();
                         countyTimer.schedule(new TimerTask(){           
                         public void run(){
                             selectedArea.add(getEnglishCounties().get(minIndex));
                          System.out.println((String)getEnglishCounties().get(minIndex));
                             getEnglishCounties().remove(getEnglishCounties().get(minIndex));
                             populateselectedArea();    
                             populateAreaList();
                             isCanAdd=true;
                             countyTimer.cancel();
                       } ,150);
       }The other JList listener is the same but the other way round. I appreciate there's quite a lot of non commented code here.
    Thanks for your help
    Craig

    I don't think you need a timer. I think your problem is that you were executing your move routine with every ListSelectionEvent.
    This is a problem because when you click in the list, you're usually firing two ListSelectionEvents: one for the item being unselected, and another for the new item being selected. If you allow multiple selections, then there will be even more.
    Instead, you should use the getValueIsAdjusting() method on the ListSelectionEvent to make sure that you're seeing the final product. That is to say, do not execute your move code until you see a ListSelectionEvent for which getValueIsAdjusting() == false.

  • JTabbedPane lose JList contents

    Hi , this is my first question in the forum :D, i have a problem with a JTabbedPane with two tabs, each with a JList in a JPanel, the problem is that i populate the Jlists in a dynamic way using a vector. the Jlist in the first index (tab) is populated first and then I select the second tab and populate the second Jlist, but when I return to the first tab the Jlist is empty, i guess because it is repainted, which method or what i need to do to keep my JList populated !!

    In the future Swing related questions should be posted in the Swing forum.
    Without seeing your code we can only guess!
    Swing components can't be shared.
    You need to create two JLists, one for each tab.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Populating table from database

    Number FoodItem Quantity Price Description
    1     Rice     1 bag     5000 Carbohydrate
    2     Beans     1 bag     4000 Protein
    3     Palm Oil 1 bottle 500 Fats & Oil
    i have a table like this in my database,need help in populating my list
    with "FoodItem" from the database when my GUI comes up.Also,want to display final result of selection in my table.
    '\n'
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import static javax.swing.GroupLayout.Alignment.*;
    import java.sql.*;
    import java.util.*;
    public class Foodtable extends JFrame {
         //private JButton finish,view;
         private JTable table;
         private DefaultTableModel model;
         private JScrollPane pane,pane1;
         private JTextField currentamount,totalamount,qtyfield;
         private JList foodlist;
         private JComboBox box;
         private String[] qtybox={"cup","mudu","bag"};
         private DefaultListModel lm;
         Connection con=null;
         Statement st=null;
         private static ResultSet rs;
         public Foodtable(){
              JPanel p1 = new JPanel();
              p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Food List",TitledBorder.CENTER,TitledBorder.TOP));
              p1.setLayout(null);
              p1.setPreferredSize(new Dimension(170,150));
              lm = new DefaultListModel();
              foodlist = new JList(lm);
              pane1 = new JScrollPane(foodlist);
              pane1.setBounds(10,20,148,180);
              p1.add(pane1);
              JLabel qty = new JLabel("Quantity:");
              qty.setBounds(10,210,60,20);
              p1.add(qty);
              qtyfield = new JTextField(5);
              qtyfield.setBounds(65,210,30,20);
              p1.add(qtyfield);
              box = new JComboBox(qtybox);
              box.setBounds(95,210,60,20);
              p1.add(box);
              JPanel p2 = new JPanel();
              p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Food Table",TitledBorder.CENTER,TitledBorder.TOP));
               model = new DefaultTableModel();
               model.addColumn("Number");
               model.addColumn("Food Item");
               model.addColumn("Quantity");
               model.addColumn("Price");
               model.addColumn("Description");
              table = new JTable(model);
              pane = new JScrollPane(table);
              pane.setPreferredSize(new Dimension(300,140));
              p2.add(pane);
              JPanel p = new JPanel();
              GroupLayout layout = new GroupLayout(p);
              p.setLayout(layout);
              layout.setAutoCreateGaps(true);
              layout.setAutoCreateContainerGaps(true);
              layout.setHorizontalGroup(layout.createSequentialGroup()
                   .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                             .addComponent(p1)
                        .addComponent(p2)
              layout.setVerticalGroup(layout.createSequentialGroup()
                   .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(p1)
                        .addComponent(p2)
              JPanel p4 = new JPanel();
              p4.setLayout(null);
              p4.setPreferredSize(new Dimension(200,30));
              /*finish = new JButton("Finish");
              finish.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
              finish.setRolloverEnabled(false);
              finish.setBounds(170,20,60,20);          
              p4.add(finish);*/
              JLabel currentlabel = new JLabel("Current Amount:");
              currentlabel.setBounds(300,10,100,20);
              p4.add(currentlabel);
              currentamount = new JTextField();
              currentamount.setBounds(395,10,50,20);
              currentamount.setEditable(false);
              p4.add(currentamount);
              JLabel total = new JLabel("Amount Spent:");
              total.setBounds(300,30,100,20);
              p4.add(total);
              totalamount = new JTextField();
              totalamount.setBounds(395,30,50,20);
              totalamount.setEditable(false);
              p4.add(totalamount);
              GroupLayout flayout = new GroupLayout(getContentPane());
              getContentPane().setLayout(flayout);
              flayout.setAutoCreateGaps(true);
              flayout.setAutoCreateContainerGaps(true);
              flayout.setHorizontalGroup(flayout.createSequentialGroup()
                   .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(p)
                        .addComponent(p4)
              flayout.setVerticalGroup(flayout.createSequentialGroup()
                   .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(flayout.createSequentialGroup()
                             .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                  .addComponent(p)
                        .addComponent(p4)
              setSize(640,460);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public static void main(String[] arg){
              new Foodtable().setVisible(true);
         public void showRecord(){
              try{
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con = DriverManager.getConnection("jdbc:odbc:food","","");
                   st = con.createStatement();
                   rs=st.executeQuery("SELECT*FROM tbl_food");
                   while(rs.next()){
                        lm.addElement(rs.getString("food_name"));
              catch(Exception sqle){
                   JOptionPane.showMessageDialog(null,"Exception.......\n" + sqle.getMessage() ,"Error Information",JOptionPane.ERROR_MESSAGE);
         /*public void query(){
              try{
                   Class.forName("com.mysql.jdbc.Driver");               
                   con = DriverManager.getConnection("jdbc:mysql://localhost/food?user=password=");
                   st = con.createStatement();
                   String sql = "SELECT foodlist.food,foodlist.description FROM foodlist";
                   rs = st.executeQuery(sql);
                   while(rs.next()){
                        lm.addElement(rs.getString(1)+'\n');
              }catch(Exception ee){
                   System.out.println(ee);
              finally{
                   try{
                        st.close();
                        con.close();
                   }catch(Exception ex){ System.err.println(ex);}
         public void actionPerformed(ActionEvent e){
              Object[] value = foodlist.getSelectedValues();
              if(e.getSource()==view){
                   query();
              if(e.getSource() == move){
                   for(int i=0;i<value.length;i++){
                        String word = (String)value;
                        //String foodclass = rs.getString("foodlist.description");
                        Vector<Object> data = new Vector<Object>();
                        data.addElement(word);
                        data.addElement(qtyfield.getText()+" "+box.getSelectedItem());
                        data.addElement("");
                        //data.addElement("foodclass");
                        model.addRow(data);

    This particular forum is about jdbc. Do you have a question about jdbc?
    If so then what specifically is it?
    If you have questions about GUIs (display, buttons, events, etc) then there are other forums for that.

  • Getting differend fonts on JList

    I was helped to do like this to get different fonts visible on JList. How ever I can't get selectable list (Jlist) of fonts shows on it's own font...
    If i create a Component and FontListCellRenderer and use FontListCellREnderers method getCellListRendererComponent(.....) I can place the return value into this new Component and add this component to JPanel...
    but how to do this so that all the fonts are shown in a list and the list added to JPanel?
    String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    Font[] fonts = new Font[fontNames.length];
    for(int idx = 0; idx < fontNames.length; idx++)
              fonts[idx] = new Font(fontNames[idx], Font.PLAIN, 12);
    JList fontList = new JList(fonts);
    fontList.setCellRenderer(new FontListCellRenderer());          
    public class FontListCellRenderer extends DefaultListCellRenderer
    public Component getListCellRendererComponent(JList list, Object value, int idx, boolean isSelected, boolean hasFocus)
    // Assume that the list is populated with Fonts...
    Font font = (Font)value;
    // Get a renderer component suitable for displaying the name of the font
    Component comp = super.getListCellRendererComponent(list, font.getName(), idx, isSelected, hasFocus);
    // Alter the renderer component to use the font
    comp.setFont(font);
    return comp;
    P_trig     

    This would not take care of all issues but have you tried changing Preferences – Interface – UI Font Size?

Maybe you are looking for

  • What's the best way to setup a media server/central storage for all of my?

    I was wondering what the best way to achieve a central media server for all my iTunes content + iPhoto's, calendar syncing and contact sharing is? This is what I currently have: iMac 20" Aluminum + External HD Backup (kids) Macbook Black (wife) Macbo

  • I want to get the correct cables

    Hello, I have a 13" MacBook and I'd like to hook it up to my 42" LCD TV to play games and watch and edit movies and pictures. It's a 42" Vizio VU42L (manual located at Vizio's Site). I have HDMI inputs and RGB PC (VGA) inputs on the back of the TV an

  • HP PSC 1410-v All-In-One - Doc. failed to print

    My HP All-In-One 1410-v printer works fine most of the time.  However, it used to print my paycheck stub from Intuit's Payroll Website.  Suddenly it refused to print that information.  it will print the first three lines and then I receive an error m

  • Intel Mac Mini & webcam

    I have a Mini and would like to use a webcam on it. I use a P/S2 keyboard and mouse and a non-Apple monitor so i can switch between the Mini & PC. I have tried using my PC cam but the Mini doesn't see it. Any ideas? This is a cross-post from the Came

  • How to modify the homepage frame work

    Hi, As i need to do the ESS homepage customization , i need to change the Overview text and Icons, for this am giving my custom tet in SPRO->Cross Apss->homepage framework->headers and area group pages->define area group pages->overview..its giving a