About  FocusTraversal  in JList

Hi all , I'm building up a mini dictionary ,I 've done the rest of my program and this is just an extra , when the user input the
character "L" into the textfield then the List of word will point to the first word of
all the words that consist "L" , so on.......as the figure in the below link :
http://i196.photobucket.com/albums/aa69/emperor1412/Question.jpgI have find out that swing has some methods about " FocusTraversal " to support JList , I've try to connect the " FocusTraversal " of my List to the " Textfield " so that the " Textfield " can control it but unsuccessfull, can anyone spend a moment to solve this problem by using anything about " FocusTraversal " , I can solve this problem by another way but I want to know how this problem can be solve by using " FocusTraversal " .
Here is the link of database for dictionary ( this file is *{color:#ff0000}compulsory{color}* to run this program):
http://6636676817799962274-a-greenmekong-com-s-sites.googlegroups.com/a/greenmekong.com/nguyenhailong/teaching/dicData.rar?attredirects=0 *( no virus )*
or
http://nguyenhailong.greenmekong.com/teaching ( file DicData.rar )
These are 5 classes of my program , just copy and buit it , it already worked :
1.Class Data
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
public class Data implements Serializable{
    private List<String> Data;
    public Data()
        Data = new Vector<String>(104966);
    public void add(String data)
        Data.add(data);
    public String get(int index)
        String entireSentence="";
        String data = Data.get(index);
        StringTokenizer seperatedWord = new StringTokenizer(data);
        List<String> temp = new ArrayList<String>();
        while(seperatedWord.hasMoreElements())
            temp.add((String)seperatedWord.nextElement());
        Iterator iterator = temp.iterator();
        while(iterator.hasNext())
            boolean flag = false;
            String word = (String)iterator.next();
            for(int k = 0 ; k < word.length(); k++ )
                if(word.charAt(k)=='\\' && word.charAt(k+1)=='n')
                    entireSentence = entireSentence +"  "+ word.substring(0, k)
                            + "\n" +"  "+ word.substring(k+2,word.length()) ;
                    flag = true;
                    break;
            if(!flag)   entireSentence += (word+"  ");
        return entireSentence;
    public List<String> getData() {
        return Data;
    public void setData(List<String> Data) {
        this.Data = Data;
2.Class DicData
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.Scanner;
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.util.Vector;
import javax.swing.JOptionPane;
* @author kaka
public class DicData implements Serializable{
    static ObjectOutputStream output;
    static ObjectInputStream input;
    private List<WordIndex> wordindex;
    private Data data;
    private int numofword=0;
    public DicData(String path) throws Exception
        boolean flag = false;
        wordindex = new Vector<WordIndex>(104966);
        data = new Data();
        try{
            Scanner in = new Scanner(new FileInputStream(path),"UTF-8");
            while(in.hasNext()) {                       
                String Line = in.nextLine();
                String Word ="";
                for(int i = 0 ;i < Line.length() ; i++ ) {
                    if(Line.charAt(i)=='[' )
                        Word = Line.substring(0, i-1);
                        Word = Word.trim();
                        Word = Word.toLowerCase();
                        break;
                    if(Line.charAt(i)==' ' && Line.charAt(i-1)=='-') {
                        if(Line.charAt(i-2) == '\t') {
                            Word = Line.substring(0, i-1);
                            Word = Word.trim();
                            Word = Word.toLowerCase();
                            break;
                        if(Line.charAt(i-2) != '\t' ) {
                            Word = Line.substring(0, i);
                            Word = Word.trim();
                            Word = Word.toLowerCase();
                            break;
            wordindex.add(new WordIndex(Word,numofword));           
            data.add(Line);
            ++numofword;
        catch(Exception exception){
            JOptionPane.showMessageDialog(null, "Invalid path");
            System.exit(1);
    public static void saveRecord(DicData dicdata) throws Exception
         try {
            output = new ObjectOutputStream(new FileOutputStream(new File("DictionaryData.ser")));
         catch ( Exception exception ){
            System.err.println( "Error opening file." );
         try{
            output.writeObject(dicdata);
            JOptionPane.showMessageDialog(null,"Database saved successfully");
         catch ( Exception exception ){
               System.err.println( "Error writing to file." );
    public static DicData loadRecord() throws Exception {
        input = new ObjectInputStream(new FileInputStream("DictionaryData.ser"));
        return (DicData) input.readObject();
    public static void closeFileoutput()
        try {
        if(output!=null)
            output.close();
        catch(Exception exception) {
            System.err.println("Error closing file");
            System.exit(1);
    public static void closeFileinput()
        try {
        if(input!=null)
            input.close();
        catch(Exception exception) {
            System.err.println("Error closing file");
            System.exit(1);
    public Data getData() {
        return data;
    public void setData(Data data) {
        this.data = data;
    public int getNumofword() {
        return numofword;
    public void setNumofword(int numofword) {
        this.numofword = numofword;
    public List<WordIndex> getWordindex() {
        return wordindex;
    public void setWordindex(List<WordIndex> wordindex) {
        this.wordindex = wordindex;
3.Class HashingDic
import java.io.Serializable;
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.swing.JOptionPane;
* @author kaka
public class HashingDic implements Serializable{
    protected Hashtable table;
    public HashingDic(DicData data)
        table = new Hashtable();
        List<WordIndex> wordindex = data.getWordindex();
        Iterator it = wordindex.iterator();
        while(it.hasNext())
            WordIndex temp = (WordIndex)it.next();
            table.put( temp.getKey(),temp.getIndex() );
    public int Search(String keyword)
        try{
        return (Integer) table.get(keyword);  
        catch(NullPointerException nullPointerException)
            JOptionPane.showMessageDialog(null,"Word not found");
            return -1;
4.Class WordIndex
import java.io.Serializable;
* To change this template, choose Tools | Templates
* and open the template in the editor.
* @author kaka
public class WordIndex implements Serializable {
    private String Key;
    private Integer Index;
    public WordIndex(){}
    public WordIndex(String word,int index)
        Key = word;
        Index = index;
    public Integer getIndex() {
        return Index;
    public void setIndex(Integer Index) {
        this.Index = Index;
    public String getKey() {
        return Key;
    public void setKey(String Key) {
        this.Key = Key;
5.Class Main
*import java.awt.BorderLayout;*
*import java.awt.Color;*
*import java.awt.Container;*
*import java.awt.Panel;*
*import java.awt.event.ActionEvent;*
*import java.awt.event.ActionListener;*
*import java.util.HashSet;*
*import java.util.Iterator;*
*import java.util.List;*
*import java.util.Set;*
*import java.util.Vector;*
*import javax.swing.JButton;*
*import javax.swing.JFileChooser;*
*import javax.swing.JFrame;*
* To change this template, choose Tools | Templates
* and open the template in the editor.
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
* @author kaka
public class Main extends JFrame implements ActionListener {
    private JButton Search;
    private JTextField TextField;
    private JList List;
    private JTextArea TextArea;
    private Container container;
    private JLabel Label;
    private JScrollPane Scroll;
    private JScrollPane ScrollPane;
    private DicData data ;
    private HashingDic hashData ;
    private Vector<String> keywords;
    Set<KeyStroke> key = new HashSet<KeyStroke>();
    //private KeyStroke keystroke;
    public Main(){
    super("Dictionary - Author : &#272;uc-Ho&agrave;ng-Giang-Group ");
    super.setResizable(false);
    public void runGraphic()
        container = this.getContentPane();
        BorderLayout layout = new BorderLayout();
        container.setLayout(layout);
        Label = new JLabel("Input word here ");
        TextField = new JTextField(20);
        TextField.addActionListener(this);
        Search = new JButton("Search");
        Search.addActionListener(this);
        Panel panel1 = new Panel();
            panel1.add(Label);
            panel1.add(TextField);
            panel1.add(Search);
        TextArea = new JTextArea( 26, 40);
        TextArea.setBackground(Color.WHITE);
        TextArea.setEditable(false); // the information about the meaning of word can not be edit
        Panel panel2 = new Panel();
        Scroll = new JScrollPane(TextArea);
            panel2.add(Scroll);
        List = new JList(keywords);
        List.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        List.setFixedCellWidth(180);
        List.addListSelectionListener(new ListSelectionListener()
            public void valueChanged(ListSelectionEvent e) {
                int index = List.getSelectedIndex();               
                TextArea.setText(data.getData().get(index));
                TextArea.setCaretPosition(0);
        ScrollPane = new JScrollPane(List);
                container.add(panel1,BorderLayout.NORTH);
                container.add(panel2,BorderLayout.EAST);
                container.add(ScrollPane,BorderLayout.WEST);
        this.setSize(700, 500);
        this.setVisible(true);
    public static void main(String args[]) throws Exception
        Main test = new Main();
        test.runSource();
        test.runGraphic();
        test.setDefaultCloseOperation(EXIT_ON_CLOSE);
    public void runSource() throws Exception
        try{
            //long start = System.currentTimeMillis();
            data = DicData.loadRecord();
            hashData = new HashingDic(data);
            keywords = new Vector<String>(104966);
            List<WordIndex> words = data.getWordindex();
            Iterator it = words.iterator();
            while(it.hasNext())
                WordIndex temp = (WordIndex) it.next();
                keywords.add(temp.getKey());
            JOptionPane.showMessageDialog(null,"Database loaded successfully ");
            DicData.closeFileoutput();
            /*long end = System.currentTimeMillis();
            JOptionPane.showMessageDialog(null,"Duration : " + (end - start)
                    + "\n Num of words : " + data.getNumofword());*/
        catch(Exception exception)
            JOptionPane.showMessageDialog(null,"Database loaded failed ");
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int result = chooser.showOpenDialog(this);
            if(result == JFileChooser.CANCEL_OPTION)   System.exit(1);
            String path = chooser.getSelectedFile().getAbsolutePath();
            //String path = JOptionPane.showInputDialog("Input path of database : ");
            //long start = System.currentTimeMillis();
            data = new DicData(path);
            hashData = new HashingDic(data);
            JOptionPane.showMessageDialog(null,"Database created successfully ");
            DicData.closeFileinput();
            DicData.saveRecord(data);
            List<WordIndex> words = data.getWordindex();
            Iterator it = words.iterator();
            keywords = new Vector<String>(104966);
            while(it.hasNext())
                WordIndex temp = (WordIndex) it.next();
                keywords.add(temp.getKey());
            /*long end = System.currentTimeMillis();
            JOptionPane.showMessageDialog(null,"Duration : " + (end - start)
                    + "\n Num of words : " + data.getNumofword());*/
    public void actionPerformed(ActionEvent e) {
        if( e.getSource() == TextField || e.getSource() == Search )
            String a = TextField.getText();
            a = a.toLowerCase();
            a = a.trim();
            int returnValue = hashData.Search(a);
            if(returnValue!=-1)
            TextArea.setText(data.getData().get(returnValue));
            TextArea.setCaretPosition(0);  //put the prompt at the begining of the text
}Edited by: keomanla on Sep 5, 2008 11:17 PM
Edited by: keomanla on Sep 5, 2008 11:17 PM
Edited by: keomanla on Sep 5, 2008 11:18 PM
Edited by: keomanla on Sep 5, 2008 11:19 PM
Edited by: keomanla on Sep 5, 2008 11:19 PM
Edited by: keomanla on Sep 5, 2008 11:22 PM
Edited by: keomanla on Sep 5, 2008 11:24 PM
Edited by: keomanla on Sep 5, 2008 11:42 PM
Edited by: keomanla on Sep 5, 2008 11:43 PM
Edited by: keomanla on Sep 6, 2008 12:43 AM

You could still use HTML, but I guess then the problem would be the image on the button.
Alternatively, you could subclass JToolTip, create the ui you want, and install it on the JList by overriding the necessary tooltip methods in JList (I think getToolTip). Search the forums (serach field on the left) for more on this approach.
A third approach would be to re-invent the wheel using JWindow and a Timer to achieve the appearance and effect you want.
ICE

Similar Messages

  • Help needed, stuck in a DnD JList problem

    Hi guys
    I got this code from internet and I was really expecting it would work, but it is not really transferring my Object to the other JList.
    I someone can help me I would appreciate that very much, below is the code, to the Model and to the Transfer.
    Model
    public class TabVernizListModel extends AbstractListModel {
        ArrayList<TabelaVerniz> lista;
        public TabVernizListModel(ArrayList<TabelaVerniz> lista) {
            this.lista = lista;
        public TabVernizListModel() {
            lista = new ArrayList<TabelaVerniz>();
        public Object getElementAt(int index) {
            Object item = null;
            if (lista != null) {
                item = lista.get(index);
            return item;
        public Integer getSelectedIndex(TabelaVerniz item) {
            int index = lista.indexOf(item);
            return index;
        public int getSize() {
            int size = 0;
            if (lista != null) {
                size = lista.size();
            return size;
        public void remove(int index) {
            fireIntervalRemoved(this, index, index);
            lista.remove(index);
        // This is not really working, does not update the 2nd List
        public void add(TabelaVerniz tabela) {
            if (lista == null) {
                lista = new ArrayList<TabelaVerniz>();
            lista.add(tabela);
            int index = this.getSelectedIndex(tabela);
            super.fireIntervalAdded(this, lista.size() - 1, lista.size() - 1);
    The Transfer:
    public class TabVernizTransferHandler extends TransferHandler {
        JList listaEsquerda;
        JList listaDireita;
        // This transfer handler needs to know about the two JLists !
        public TabVernizTransferHandler(JList leftList, JList rightList) {
            super();
            listaEsquerda = leftList;
            listaDireita = rightList;
        @Override
        public boolean importData(JComponent component, Transferable trasferedObject) {
            JList lista = (JList) component;
            try {
                int sourceIndex = Integer.parseInt((String) trasferedObject.getTransferData(DataFlavor.stringFlavor));
                // figure out which is the source and which is the dest.
                TabVernizListModel source;
                TabVernizListModel dest;
                if (lista == listaEsquerda) {
                    source = (TabVernizListModel) listaDireita.getModel();
                    dest = (TabVernizListModel) listaEsquerda.getModel();
                } else {
                    source = (TabVernizListModel) listaEsquerda.getModel();
                    dest = (TabVernizListModel) listaDireita.getModel();
                // get the source object
                TabelaVerniz tabela = (TabelaVerniz) source.getElementAt(sourceIndex);
                // add it to the other model.
                dest.add(tabela);
                // and remove from the source
                source.remove(sourceIndex);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("Import failed!");
                return (false);
            return (true);
        @Override
        protected Transferable createTransferable(JComponent c) {
            JList jl = (JList) c;
            // we want the currently selected index
            Integer index = new Integer(jl.getSelectedIndex());
            // and we transfer it as a string
            Transferable t = new StringSelection(index.toString());
            return t;
        @Override
        public int getSourceActions(JComponent c) {
            return MOVE;
        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (flavors.getHumanPresentableName().equals("Unicode String")) {
    return (true);
    return (false);
    }Can anyone point what is wrong here?
    When I drag from the left list to the right list it just don't drop.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    The Swing tutorial on Drag and Drop has a working example with a JList.

  • Getting information about an object from JList

    Hi
    I have created a movie application and i have a JList displaying all registered movies, it uses a DefaultListModel to display these.
    I want to be able to click on an element in the JList and then push a button called "Show movie details" to display all information about the selected movie.'.
    Every new movie is added to the DefaultListModel as an object with "Titlle", "Genere" etc. If someone click on a movie, what do i do to get information about which object that was clicked. All i can see is that integers can be returned with the getSelectedIndex/Value methods. If i use one of these methods to get the object from the DefaultListModel, that would work i guess, but what when someone deletes a movie in the middle of the JList, then the indexes wouldnt match.
    Can someone help me out here? :)

    I get a big fat exception when trying to cast the returned object to a Movie object which im using.
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.S
    tring cannot be cast to Movie
    ...sure that this is the way to do it? If so, what am i doing wrong..

  • About JList and ScrollBar

    hi i wanna ask about JList class. i've put JList on JFrame.
    and set JFrame layout to NULL after i've created JList with
    everything but without ScrollBar. after i've created a ScrollPane
    with parameter (List) but nothing changed. can u help me ?
    how can i add a ScrollBar to a List ??
    Thanks...

    I did nearly that exact thing recently. Here is a snippet of code I used. This code appears in the constructor of a JDialog.
    JList list = new JList(my_data);
    list.setMaximumSize(new Dimension((int)(m_font_list.getPreferredSize().getWidth()),300));
    JScrollPane scroll_pane = new JScrollPane(list);
    getContentPane().add(scroll_pane);

  • Very Simple question about JList

    Hi,
    I am newbie to Java, and I want to show a couple of items in JList Control, but it doesn't show up, anyone can help me. When I use system.out to printout the contents of the ListModel, it does tell me that those items are in it.
    Thanks a lot!!!!
    Code are like this:
    import java.lang.*;
    import javax.swing.*;
    public class listExample extends javax.swing.JApplet {
    public void init(){
    String[] data={"one", "two", "three", "four"};
    jList1=new JList(data);
    for(int i=0; i<jList1.getModel().getSize(); i++)
    System.out.println(jList1.getModel().getElementAt(i));
    public listExample() {
    initComponents();
    private void initComponents() {
    jList1 = new javax.swing.JList();
    getContentPane().add(jList1, java.awt.BorderLayout.CENTER);
    // Variables declaration - do not modify
    private javax.swing.JList jList1;
    // End of variables declaration

    The objects in your list probably don't know how to display themselves. To do this you must overload the toString method that is originally in java.lang.Object. So basically if you have an object with a String for a first name and last name, for example, you would write a toString() method that looks something like this:
    public String toString() {
    return firstName + " " + lastName;
    When you put this object in a list the JList will use the toString method automatically to place text in teh JList object.
    Hope it helps.

  • A question about JList (URGENT)

    I have a jtextfield that you can write anything on, another jtextfield that only accepts integers that are greater than 0 , a Jbutton, and a JList.
    I wanna add a listener for the JButton so that whenever it is pressed, the String in the first textfield will be put in the list in x number of times.
    x = the integer in the second textfield
    THANKS SO MUCH!!!

    In the actionlistener for the button:
    get the value from the Text JTextField, if empty exit.
    get and convert the value from the Integer JTextField, if 0 or not a number then exit.
    get the model (DefaultTableModel) from the JList.
    call the model.addElement(Object) passing the value from the Text JTextField in a loop controlled by the value in the Integer JTextField.
    Dave

  • About the focus changing of jlist

    I am using a jlist to show note types and a jtable to show all the notes of the current types,and I can edit the notes in the jtable.Before I change the selection of the item of the types,I need to determine if the notes have changed ,if the data changes a confirm dialog to prompt you to save will be shown,if I select cancel the selection of the item of the types should keep original for the app querys db and displays related data when types selection changing.I want to know how to show the saving confirm dialog before the item selection change and if I select cancel,the selection won't be changed,it will be changed only if I select yes or no ,cause if the item change another query will be done.I am looking for such a listener in javadoc but failed.
    thanks.
    Edited by: fxbird on Jul 17, 2008 7:18 AM

    this is so brittle, if you breathe on it, it'll break.
    anyway, it might give you something to play around with
    (when opened, click any item for selection, then click another item)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        String[] cities = {"London","Madrid","New York","Rome","Sydney","Toronto","Washington"};
        final DefaultListModel listModel = new DefaultListModel();
        final JList list = new JList(listModel);
        for(int x = 0; x < cities.length; x++) listModel.addElement(cities[x]);
        JScrollPane sp = new JScrollPane(list);
        JFrame f = new JFrame();
        f.getContentPane().add(sp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        final int rowHeight = list.getCellBounds(0,0).height;
        MouseListener[] listeners = list.getMouseListeners();
        for(int x = 0, y = listeners.length; x < y; x++) list.removeMouseListener(listeners[x]);
        list.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            int oldSelection = list.getSelectedIndex();
            int selection = me.getY()/rowHeight;
            int maxSelection = listModel.size()-1;
            if(selection > maxSelection) selection = maxSelection;
            if(oldSelection > -1)
              int response = JOptionPane.showConfirmDialog(null,"Changes not saved!!\n\nContinue?","Danger Will Robinson",
                                                JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
              if(response != JOptionPane.YES_OPTION) return;
            list.setSelectedIndex(selection);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • About JLIst and ListSelectionListener

    hello to everyone..
    I want to ask hoe to work th epublic void valueChanged(ListSelectionEvent e){} because i made a JList which connect with images (canvas)...
    I try to used a valueChanged but it doesn't done anything...
    public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (f.list.getSelectedIndex() == -1) {
                //No selection: disable delete, up, and down buttons.
                    BtDelete.setEnabled(false);
                } else if (f.list.getSelectedIndices().length > 1) {
                //Multiple selection: disable up and down buttons.
                    BtDelete.setEnabled(true);
                } else {
                //Single selection: permit all operations.
                    BtDelete.setEnabled(true);   
        }i try to do something easy to see if it works... why it not works and how to connect it with my images the path(name) of image.
    Thanx in advance..

    yes i add the ListSelectionListener to the JList..
    Also i used commands from the tutorial.
    i made and the system.out.println(...) but it not
    invoked...
    i don't know why? i used the steps of the tutorial
    sides but nothingNow we have two choices: We can continue guessing what your problem might be, or you can post a small sample program that demonstrates this behavior (or should I say non-behavior?).
    The latter approach has several advantages: while preparing that small sample program you might very well discover the problem yourself. And even if you don't discover the problem yourself, chances are that someone here will spot the error as soon as they see your code. Plus it would save the forum from a stream of posts of the form "Did you do this?" "Yes I did that." "Well did you that then?" "Yes I did that too".

  • 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

  • How to add words from a JTextField to a JList

    Im working on my final project for Java programming class using JApplet.
    Im trying to create a spelling test/wordfind
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.
    then click the "Start" Button and have the all the words from the JList be put in random stops in a panel and fill around all the words with random letters.
    then when the user clicks on the letter of the words they are finding it will change colors if they click on it again it will change back to its original color.
    So far I have my layout set up its adding the proper Listeners and events to achieve the desired results.
    I know this is way more advanced than what My Instructor is even teacher but I am very interested in Java and want to learn a lot more about it.
    If anyone has suggestions or know where i can find the information Im looking for please let me know.
    Thanks
    Code I have so Far:
    * @(#)SpellingTest.java
    * SpellingTest Applet application
    * @author
    * @version 1.00 2010/11/10
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SpellingTest extends JApplet implements ActionListener {
         Image img;
         ImageIcon icon;
         private Image title;
         JTextField word;
         JButton addWord;
         JLabel label;
         JList wordList;
         public void init() {//opening init
                   getContentPane().setLayout(null);
                   getContentPane().setBackground(Color.WHITE);
                   title = getImage(getDocumentBase(), "title.jpg");
                   //The text field
                   word = new JTextField();
                   word.setLocation(190,100);
                   word.setSize(85,30);
                   getContentPane().add(word);
                   word.addActionListener(this);
                   //The addWord button
                   addWord = new JButton("ADD");
                   addWord.setLocation(295, 100);
                   addWord.setSize(90,30);
                   getContentPane().add(addWord);
                   addWord.setBackground(new Color(146, 205, 220));
                   addWord.addActionListener(this);
                   //The label
                   label = new JLabel("Type your spelling words:");
                   label.setLocation(25, 65);
                   label.setSize(250,100);
                   getContentPane().add(label);
                   label.setForeground(new Color(146, 205, 220));
                   //The List
                   wordList = new JList();
                   JScrollPane scrollPane = new JScrollPane(wordList,
                   ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   scrollPane.setLocation(25,150);
                   scrollPane.setSize(150,300);
                   getContentPane().add(scrollPane);
         }//closing init
         public void actionPerformed (ActionEvent ae){
              Object obj = ae.getSource();
              String text = word.getText();
              if (obj == addWord){
                   if (text.length()>0);
                   wordList.addString("");
         public void paint(Graphics g) {
              super.paint(g);
    }

    Read the first posting titled "Welcome to the new home" to learn how to use code tags. Then you can edit your posting so the code is formatted and readable.
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.Read the JList API and follow the link to the Swing tutoral on "How to Use Lists" where you will find a working example.
    So far I have my layout Actually you haven't. You should learn how to use layout managers. Again the Swing tutorial explains what layout managers are and provides working example of using them.
    I am very interested in Java and want to learn a lot more about it.A great place to start is by read tutorials because they always contain working example. Here are some [url http://download.oracle.com/javase/tutorial/]Java tutorrial.

  • Need help in storing data from JList into a vector

    need help in doing the following.-
    alright i click a skill on industryskills Jlist and press the add button and it'll be added to the applicantskills Jlist. how do i further store this data that i added onto the applicantskills JList into a vector.
    here are the codes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.text.*;
    import java.util.*;
    import java.util.Vector;
    import javax.swing.JScrollPane.*;
    //import javax.swing.event.ListSelectionListener;
    public class Employment extends JFrame
            //declare class variables
            private JPanel jpApplicant, jpEverything,jpWEST, jpCENTRE, jpEAST, jpAddEditDelete,
                                       jpCentreTOP, jpCentreBOT, jpEastTOP, jpEastCENTRE, jpEastBOT,
                                       jpBlank1, panel1, panel2, panel3, panel4,jpBottomArea,
                                       jpEmptyPanelForDisplayPurposes;
            private JLabel jlblApplicantForm, jlblAppList, jlblName, jlblPhone,
                                       jlblCurrentSalary, jlblPassword, jlblDesiredSalary,
                                       jlblNotes, jlblApplicantSkills, jlblIndustrySkills,
                                       jlblBlank1, jlblBlank2, ApplicantListLabel,
                                       NotesListLabel, ApplicantSkillsLabel,
                                       IndustrySkillsLabel,jlblEmptyLabelForDisplayPurposes;  
            private JButton jbtnAdd1, jbtnEdit, jbtnDelete, jbtnSave, jbtnCancel,
                                            jbtnAdd2, jbtnRemove;
            private JTextField jtfName, jtfPhone, jtfCurrentSalary, jtfPassword,
                                               jtfDesiredSalary;
              private JTabbedPane tabbedPane;
            private DefaultListModel /*listModel,*/listModel2;
              String name,password,phone,currentsalary,desiredsalary,textareastuff,NotesText;
              String selectedname;
            final JTextArea Noteslist= new JTextArea();;
            DefaultListModel listModel = new DefaultListModel();
            JList ApplicantSkillsList = new JList(listModel);
           private ListSelectionModel listSelectionModel;
            JList ApplicantList, /*ApplicantSkillsList,*/ IndustrySkillsList;
            //protected JTextArea NotesList;    
                    //Vector details = new Vector();
                  Vector<StoringData> details = new Vector<StoringData>();             
                public static void main(String []args)
                    Employment f = new Employment();
                    f.setVisible(true);
                    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    f.setResizable(false);
                }//end of main
                    public Employment()
                            setSize(800,470);
                            setTitle("E-commerce Placement Agency");
                                  Font listfonts = new Font("TimesRoman", Font.BOLD, 12);
                            JPanel topPanel = new JPanel();
                            topPanel.setLayout( new BorderLayout() );
                            getContentPane().add( topPanel );
                            createPage1();
                            createPage2();
                            createPage3();
                            createPage4();
                            tabbedPane = new JTabbedPane();
                            tabbedPane.addTab( "Applicant", panel1 );
                            tabbedPane.addTab( "Job Order", panel2 );
                            tabbedPane.addTab( "Skill", panel3 );
                            tabbedPane.addTab( "Company", panel4 );
                            topPanel.add( tabbedPane, BorderLayout.CENTER );
            public void createPage1()//PAGE 1
                 /*******************TOP PART********************/
                            panel1 = new JPanel();
                            panel1.setLayout( new BorderLayout());
                                  jpBottomArea = new JPanel();
                                  jpBottomArea.setLayout(new BorderLayout());
                            jpApplicant= new JPanel();
                            jpApplicant.setLayout(new BorderLayout());
                            Font bigFont = new Font("TimesRoman", Font.BOLD,24);
                            jpApplicant.setBackground(Color.lightGray);
                            jlblApplicantForm = new JLabel("\t\t\t\tAPPLICANT FORM  ");
                            jlblApplicantForm.setFont(bigFont);
                            jpApplicant.add(jlblApplicantForm,BorderLayout.EAST);
                            panel1.add(jpApplicant,BorderLayout.NORTH);
                            panel1.add(jpBottomArea,BorderLayout.CENTER);
           /********************************EMPTY PANEL FOR DISPLAY PURPOSES*************************/
                               jpEmptyPanelForDisplayPurposes = new JPanel();
                               jlblEmptyLabelForDisplayPurposes = new JLabel(" ");
                               jpEmptyPanelForDisplayPurposes.add(jlblEmptyLabelForDisplayPurposes);
                               jpBottomArea.add(jpEmptyPanelForDisplayPurposes,BorderLayout.NORTH);
           /*****************************************WEST*********************************/             
                            jpWEST = new JPanel();                 
                            jpWEST.setLayout( new BorderLayout());
                            //Applicant List
                                  listModel2=new DefaultListModel();
                                  ApplicantList = new JList(listModel2);
                                listSelectionModel = ApplicantList.getSelectionModel();
                                listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
                                JScrollPane scrollPane3 = new JScrollPane(ApplicantList);
                                  ApplicantList.setPreferredSize(new Dimension(20,40));
                                 scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);                                             
                                scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            ApplicantListLabel = new JLabel( "Applicant List:");
                            jpWEST.add(ApplicantListLabel,"North"); 
                            jpWEST.add(scrollPane3,"Center");
                            jpBottomArea.add(jpWEST,BorderLayout.WEST);
                            /*********CENTRE*********/
                            jpCENTRE = new JPanel();
                            jpCENTRE.setLayout(new GridLayout(2,1));
                            jpCentreTOP = new JPanel();
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            jpCENTRE.add(jpCentreTOP);
                            jpCentreTOP.setLayout(new GridLayout(6,2));
                              //Creating labels and textfields
                            jlblName = new JLabel( "Name:");
                            jlblBlank1 = new JLabel ("");
                            jtfName = new JTextField(18);
                            jlblBlank2 = new JLabel("");
                            jlblPhone = new JLabel("Phone:");
                            jlblCurrentSalary = new JLabel("Current Salary:");
                            jtfPhone = new JTextField(13);
                            jtfCurrentSalary = new JTextField(7);
                            jlblPassword = new JLabel("Password:");
                            jlblDesiredSalary = new JLabel("Desired Salary:");
                            jtfPassword = new JTextField(13);
                            jtfDesiredSalary = new JTextField(6);
                              //Add labels and textfields to panel
                            jpCentreTOP.add(jlblName);
                            jpCentreTOP.add(jlblBlank1);
                            jpCentreTOP.add(jtfName);
                            jpCentreTOP.add(jlblBlank2);
                            jpCentreTOP.add(jlblPhone);
                            jpCentreTOP.add(jlblCurrentSalary);
                            jpCentreTOP.add(jtfPhone);
                            jpCentreTOP.add(jtfCurrentSalary);
                            jpCentreTOP.add(jlblPassword);
                            jpCentreTOP.add(jlblDesiredSalary);
                            jpCentreTOP.add(jtfPassword);
                            jpCentreTOP.add(jtfDesiredSalary);
                            //Noteslist
                            jpCentreBOT = new JPanel();
                            jpCentreBOT.setLayout( new BorderLayout());
                            jpCENTRE.add(jpCentreBOT);
                            jpBlank1 = new JPanel();
                             //     Noteslist = new JTextArea(/*Document doc*/);
                            JScrollPane scroll3=new JScrollPane(Noteslist);
                                scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                                scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                            NotesListLabel = new JLabel( "Notes:");
                            jpCentreBOT.add(NotesListLabel,"North"); 
                            jpCentreBOT.add(scroll3,"Center");
                            jpCentreBOT.add(jpBlank1,"South");
                            jpBottomArea.add(jpCENTRE,BorderLayout.CENTER);
                            /**********EAST**********/
                            //Applicant Skills Panel
                            //EAST ==> TOP
                            jpEAST = new JPanel();
                            jpEAST.setLayout( new BorderLayout());
                            jpEastTOP = new JPanel();
                            jpEastTOP.setLayout( new BorderLayout());
                            ApplicantSkillsLabel = new JLabel( "Applicant Skills");
                            JScrollPane scrollPane1 = new JScrollPane(ApplicantSkillsList);
                               scrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                              scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);                                             
                            ApplicantSkillsList.setVisibleRowCount(6);
                            jpEastTOP.add(ApplicantSkillsLabel,"North"); 
                            jpEastTOP.add(scrollPane1,"Center");
                            jpEAST.add(jpEastTOP,BorderLayout.NORTH);
                            jpBottomArea.add(jpEAST,BorderLayout.EAST);
                            //Add & Remove Buttons
                            //EAST ==> CENTRE
                            jpEastCENTRE = new JPanel();
                            jpEAST.add(jpEastCENTRE,BorderLayout.CENTER);
                            jbtnAdd2 = new JButton("Add");
                            jbtnRemove = new JButton("Remove");
                            //add buttons to panel
                            jpEastCENTRE.add(jbtnAdd2);
                            jpEastCENTRE.add(jbtnRemove);
                            //add listener to button
                           jbtnAdd2.addActionListener(new Add2Listener());
                           jbtnRemove.addActionListener(new RemoveListener());
                            //Industry Skills Panel
                            //EAST ==> BOTTOM
                            jpEastBOT = new JPanel();
                            jpEastBOT.setLayout( new BorderLayout());
                           String[] data = {"Access97", "Basic Programming",
                           "C++ Programming", "COBOL Programming",
                           "DB Design", "Fortran programming"};
                           IndustrySkillsList = new JList(data);
                           JScrollPane scrollPane = new JScrollPane(IndustrySkillsList);
                           scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                             
                           scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                           IndustrySkillsLabel = new JLabel( "Industry Skills:");
                           jpEastBOT.add(IndustrySkillsLabel,"North"); 
                           jpEastBOT.add(scrollPane,"Center");
                           jpEAST.add(jpEastBOT,BorderLayout.SOUTH);
                            //BOTTOM
                            jpAddEditDelete= new JPanel();
                            jbtnAdd1=       new JButton("Add");
                            jbtnEdit=       new JButton("Edit");
                            jbtnDelete=     new JButton("Delete");
                            jbtnSave=       new JButton("Save");
                            jbtnCancel=     new JButton("Cancel");
                            jpAddEditDelete.add(jbtnAdd1);
                            jpAddEditDelete.add(jbtnEdit);
                            jpAddEditDelete.add(jbtnDelete);
                            jpAddEditDelete.add(jbtnSave);
                            jpAddEditDelete.add(jbtnCancel);
                               jbtnEdit.addActionListener(new EditListener());
                               jbtnDelete.addActionListener(new DeleteListener());
                                jbtnEdit.addActionListener(new EditListener());
                            jbtnAdd1.addActionListener(new Add1Listener());
                            jbtnCancel.addActionListener(new CancelListener());
                            jpBottomArea.add(jpAddEditDelete,BorderLayout.SOUTH);
            public void createPage2()//PAGE 2
                    panel2 = new JPanel();
                    panel2.setLayout( new GridLayout(1,1) );
                    panel2.add( new JLabel( "Sorry,under construction" ) );
            public void createPage3()//PAGE 3
                    panel3 = new JPanel();
                    panel3.setLayout( new GridLayout( 1, 1 ) );
                    panel3.add( new JLabel( "Sorry,under construction" ) );
            public void createPage4()//PAGE 4
                    panel4 = new JPanel();
                    panel4.setLayout( new GridLayout( 1, 1 ) );
                    panel4.add( new JLabel( "Sorry,under construction" ) );
            public class Add1Listener implements ActionListener
            public void actionPerformed(ActionEvent e)
                    name = jtfName.getText();
                    password = jtfPassword.getText();
                    phone = jtfPhone.getText();
                    currentsalary = jtfCurrentSalary.getText();
                    int i= Integer.parseInt(currentsalary);
                    desiredsalary = jtfDesiredSalary.getText();
                    int j= Integer.parseInt(desiredsalary);
                       StoringData person = new StoringData(name,password,phone,i,j);
                   //     StoringData AppSkillsList = new StoringData(listModel);
                    details.add(person);
                 //     details.add(AppSkillsList);
                  listModel2.addElement(name);
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");
    //                NotesList.setText("");
            public class Add2Listener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                           String temp1;
                           temp1 = (String)IndustrySkillsList.getSelectedValue();
                           listModel.addElement(temp1);
            public class RemoveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            int index = ApplicantSkillsList.getSelectedIndex();
                                listModel.remove(index);
            public class EditListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                            jtfName.setEditable(true);
                            jtfPassword.setEditable(true);
                            jtfPhone.setEditable(true);
                            jtfCurrentSalary.setEditable(true);
                            jtfDesiredSalary.setEditable(true);
                            Noteslist.setEditable(true);
                            jbtnAdd2.setEnabled(true);               
                            jbtnRemove.setEnabled(true);
                            jbtnSave.setEnabled(true);
                            jbtnCancel.setEnabled(true);                     
            public class DeleteListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                        int index1 = ApplicantList.getSelectedIndex();
                            listModel2.remove(index1);
            public class SaveListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
            public class CancelListener implements ActionListener
                    public void actionPerformed(ActionEvent e)
                    jtfName.setText("");
                    jtfPassword.setText("");
                    jtfPhone.setText("");
                    jtfCurrentSalary.setText("");
                    jtfDesiredSalary.setText("");                         
            public class SharedListSelectionHandler implements ListSelectionListener
            public void valueChanged(ListSelectionEvent e)
             selectedname =ApplicantList.getSelectedValue().toString();
             StoringData selectedPerson = null;
             jtfName.setEditable(false);
             jtfPassword.setEditable(false);
             jtfPhone.setEditable(false);
             jtfCurrentSalary.setEditable(false);
             jtfDesiredSalary.setEditable(false);                                 
             Noteslist.setEditable(false);
             jbtnAdd2.setEnabled(false);               
             jbtnRemove.setEnabled(false);
             jbtnSave.setEnabled(false);
             jbtnCancel.setEnabled(false);
                   for (StoringData person : details)
                          if (person.getName1().equals(selectedname))
                                 selectedPerson = person;
                                 jtfName.setText(person.getName1());
                                 jtfPassword.setText(person.getPassword1());
                              jtfPhone.setText(person.getPhone1());
                              //String sal1 = Integer.parseString(currentsalary);
                             // String sal2 = Integer.parseString(desiredsalary);
                             // jtfCurrentSalary.setText(sal1);
                             // jtfDesiredSalary.setText(sal2);
                                 break;
                   //     if (selectedPerson != null)
    }

    Quit posting 300 line programs to ask a question. We don't care about your entire application. We only care about code that demonstrates your current problem. We don't want to read through 300 lines to try and find the line of code that is causing the problem.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    Here is a simple SSCCE. Now make your changes and if you still have problems you have something simple to post. If it works then you add it to your real application.
    Learn to simplify your problem by simplifying the code.
    import java.awt.*;
    import javax.swing.*;
    public class ListTest2 extends JFrame
         JList list;
         public ListTest2()
              String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
              list = new JList( numbers );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListTest2 frame = new ListTest2();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • Question about How to Use Custom CellEditors

    Hi:
    I have been trying to implement something like this: I have a JPanel, and when you double-click a particular spot on it, I want a textbox to appear. Currently, I am implementing it by using an undecorated JDialog that contains a JTextField in it (such that the text field occupies all the space in the dialog, i.e. you can't even tell that there is a dialog). This seems like a hack to me.
    Another alternative that I have been thinking about is using layered panes, and hiding the textfield below the jpanel, and only bringing it to the front when the user double-clicks.
    Then, I stumbled onto custom celleditors. Now, it seems that everyone is using them in JTables, JLists, JComboBoxes, etc. and I was wondering if it is something that I can use with a JPanel.
    Can anyone comment on the implementations I am considering, as well as using custom celleditors with a JPanel?
    Thanks in advance,
    LordKelvan

    Still don't understand your requirement. Does the text field stay there or disappear after the data is entered? If it disappears, then how do you change the value, do you have to click on the exact same pixel again?
    Maybe you could use a MouseListener and then display a JOptionPane or JDialog to prompt for the information. Or if you want to display a JTextField then add a JTextField to the panel and then when the user enters the data by using the enter key or by clicking elsewhere on the GUI you remove the text field from the panel.

  • JList - drag and drop

    Hi,
    I'm struggling with getting my program outfitted with a drag and drop function in and between a few JList components. (I'm using NetBeans IDE 6.7)
    I have four JLists of which only one I want to enabled drag and drop rearrangement of the strings. Furthermore I would like to enable dragging from the other three lists into the rearrangeable list (which may be empty!).
    I've searched for answers but I just can't manage to translate the answers on other forums into a usable solution for my program... I am relatively new to Java and NetBeans, so I would appreciate if you could keep the answers simple... (if possible).
    What I know about this problem already:
    - if i set dragEnabled to true, I can drag text into e.g. a TextField without further complications

    JTextComponents have preinstalled TransferHandlers that make it possible to simply call setDragEnabled(true) and you are good to go. However, with most other components, you need to install a custom TransferHandler (ie call list.setTransferHandler() ) to get the job done.
    Here is a sample of the code you need: ListTransferHandler
    ICE

  • How to scroll JList to bottom

    I have a JList on a JScrollPane, and it updates in real-time.
    As the data fills the pane, I want it to scroll to the bottom all the time,
    but it stays at the top. I update as follows:
    String voltString[]=new String[someNumber];
    // Set the strings to stuff--code omitted
    voltList.setListData(voltStrings);
    voltList.ensureIndexIsVisible(voltStrings.length);But it doesn't work. The API for ensureIndexIsVisible says something
    about a JViewPort, but I am not sure what it means--I have it on a
    JScrollPane, not a JViewPort.

    works OK like this
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing extends JFrame
      int counter = 0;
      javax.swing.Timer timer;
      public Testing()
        setLocation(200,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final DefaultListModel lm = new DefaultListModel();
        final JList list = new JList(lm);
        JScrollPane sp = new JScrollPane(list);
        sp.setPreferredSize(new Dimension(100,150));
        getContentPane().add(sp);
        pack();
        setVisible(true);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            lm.addElement(counter);
            counter++;
            list.ensureIndexIsVisible(lm.size()-1);
            if(counter > 100) timer.stop();}};
        timer = new javax.swing.Timer(100,al);
        timer.start();
      public static void main(String[] args){new Testing();}
    }

  • Huge combo boxes in JFileChooser/JList text truncated in 1.4.0

    Hi there,
    We have an application which works fine on Sun JRE 1.3.1
    Recently we started supporting Sun JRE 1.4.0
    But we have some problems with GUI in Sun JRE 1.4.0
    In the JFileChooser dialog the combo box for Folder name
    and file filter is atleast twice as big as normal in when
    using JRE 1.4.0. This seems to be happening only in some particular
    machines. And if we run the application using JRE 1.3.1, on the machine which has problems with JRE 1.4.0, everything works fine.
    Also we use a JList with a custom cell rendered in the application.
    the cell renderer returns a JLabel component with "monospaced" font set in it. In some machines (same machines which has the JFileChooser problem) the upper half of each item in the JList is truncated. This also works fine is we use JRE 1.3.1 on the same machine.
    Please help me if you have any info on these issues.
    Any pointers to related issues on this forum or bug database is highly appreciated.
    Thanks in adance

    Hehe. Give it more time. Could you explain more about what you mean?
    You have a form with the select combo box in it. The user chooses a value from the combo box. Then submits the form. You want to put the value of the option inside the sql statement right? Not the words displayed by the option, but the item you put in the value section right?
    If so, its rather easy:
    query = "INSERT INTO Table VALUE( comboType, \""+request.getParameter( "text")+"\"); The \" might not be necessary depending on how the value is stored.

Maybe you are looking for

  • LORD: ERP Quotation passing custom fields to ERP system

    Hi Gurus I extended the ERP quotation screen with custom fields which are same like ERP fields using AET and generated the setter and getter and methods for those fields in CRM system , but after entering the values into the custom fields and pressin

  • Save as swf file using httpconnection and file io

    I have one application which is fatch the swf file from web and i want to save as in same to swf file format. when i have fatch the swf file and save as .swf format i have unable to view as flash animation in browser and micromedia. Anyone suggest me

  • Printing error in yahoo finance. I have to go to I.E. to print. This started about a week ago.

    When I try to print a stock portfolio in Yahoo Finance I get an icon at the bottom of the page taking me to "library. documents" on my hard drive and asking me to save the "xps" file. This started about a week ago. I have to go to I.E. to print the l

  • Using Record Statistics for session/Interface inside of package

    Oracle DB / ODI. I have a package starting with Interface. In the second step I want to know how many records was inserted/updated by first interface. Let say those numbers will be used on second interface. How can I do that? Is there any way to get

  • Music doesn't loop seemless

    Hi to all and thanks for this forum. I'm almost new to Encore (have 2.0). I created a nearly 8 seconds audio to loop very well and put it in the start menu. I loops, but each time it loops I notices something like 1 o 2 seconds of silence. Any help w