JTable Combobox dependencies

i have a jtable with 2 column
each column has JComboBox for CellRenderer
the second column is depends on the first one
means
if in row 1 , first combo select value 1 , i should have in second combobox thous values 11,12,13,14
if in row 2 , first combo select value 2 , i should have in second combobox thous values 21,22,23,24
i wanted to listen to ActionEvent ,ItemEvent ,PopupMenuEvent on the combobox on the Second Combobox
and before the second combobox is showing replace all available values in the second combobox
but no matter what property i ask for i cant tell if the combobox is in open or is not
cause each time i get 2 events
one for opening second combobox other for selecting value in it
please help me

I have no idea how a HierarchyListener would be used to solve this problem.
FYI, the [Combo Box Table Editor|http://www.camick.com/java/blog.html?name=combo-box-table-editor] was created for this situation.

Similar Messages

  • JTable Combobox editor with PrppertychangeListener

    Hello,
    I need a help from experts.
    I have a JTable. In the java table i need to have a ComboBox editor for example on the second column. And when i am changing value in the combobox i need to to do some calculations in JTable object.
    To setup a PropertyChangeListener on combo object is not what i want, because i can not make calcultions inside JTable.
    I need ComboBox based editor for JTable with property change listener.
    Can anybody point me to some example o sugest something?
    Thanks a lot

    Sollution
    package kelias.table.editor;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JTable;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.Component;
    import kelias.ComboBox.MyDBComboBox;
    Implements a cell editor that uses a formatted text field
    to edit Integer values.
    public class CarJobEditor extends DefaultCellEditor implements ItemListener
    MyDBComboBox comboJobs;
    //Darbo kiekis
    String jobQuantity=new String();
    //Lentel�
    JTable tableTmp;
    //Einamoji eilut�
    int rowTmp;
    int jobQColNumber;
    int resultColIndex;
    public CarJobEditor(int jobQColNumber,int resultColIndex)
    super(new MyDBComboBox());
    this.jobQColNumber=jobQColNumber;
    this.resultColIndex=resultColIndex;
    comboJobs = (MyDBComboBox) getComponent();
    comboJobs.loadData(kelias.db.DBStrings.selectJobsForCombo());
    comboJobs.addItemListener(this);
    //Override to invoke setValue on the formatted text field.
    public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected,int row, int column)
         jobQuantity=(String)table.getValueAt(row,jobQColNumber);
         this.tableTmp=table;
         this.rowTmp=row;
    MyDBComboBox tmp = (MyDBComboBox)super.getTableCellEditorComponent(table, value, isSelected, row, column);
    tmp.setSelectedItem(value);
    return tmp;
    public void itemStateChanged(ItemEvent event)
         if(event.getStateChange() == ItemEvent.SELECTED)
              if (!this.jobQuantity.equals(""))
                   float price=kelias.db.DBGetData.selectJobPricePM(comboJobs.getSelectedItem());
                   float quantity=Float.parseFloat((String)jobQuantity);
                   float f = (float) (Math.round(price*quantity*100.0f)/100.0f);
                   tableTmp.setValueAt(f,rowTmp,resultColIndex);
    }

  • JTable + combobox

    Hi,
    I'm new with JTable.
    I've a JTable where I added a comboBox.
    I need to open a Dialog box by selecting an option from the comboBox.
    Please let me know how can I do that...
    thanks in advance.
    here is how I added my combobox
    code
              //Set up the editor for the cells.
              JComboBox comboBox = new JComboBox(items);
              column.setCellEditor(new DefaultCellEditor(comboBox));
              //DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              ComboBoxRenderer renderer = new ComboBoxRenderer(items);
              column.setCellRenderer(renderer);
    code
    Edited by: user1202074 on Aug 4, 2011 10:14 AM
    Edited by: user1202074 on Aug 4, 2011 10:25 AM

    Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
    Then edit your post and format the code correctly.

  • JTable  - ComboBox problem

    From using a tutorial from a website.. it places a JComboBox in first column the ComboBox elements are: "item1", "item2", "item3", all rows are given these values.
    How can I do it such that JComboBox have different values for each row?
    JTable table = new JTable();
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        // Add some columns
        model.addColumn("A", new Object[]{"item1"});
        model.addColumn("B", new Object[]{"item2"});
        // These are the combobox values
        String[] values = new String[]{"item1", "item2", "item3"};
        // Set the combobox editor on the 1st visible column
        int vColIndex = 0;
        TableColumn col = table.getColumnModel().getColumn(vColIndex);
        col.setCellEditor(new MyComboBoxEditor(values));
        // If the cell should appear like a combobox in its
        // non-editing state, also set the combobox renderer
        col.setCellRenderer(new MyComboBoxRenderer(values));
        public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
            public MyComboBoxRenderer(String[] items) {
                super(items);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                if (isSelected) {
                    setForeground(table.getSelectionForeground());
                    super.setBackground(table.getSelectionBackground());
                } else {
                    setForeground(table.getForeground());
                    setBackground(table.getBackground());
                // Select the current value
                setSelectedItem(value);
                return this;
        public class MyComboBoxEditor extends DefaultCellEditor {
            public MyComboBoxEditor(String[] items) {
                super(new JComboBox(items));
        }

    thank you for informing me, i will be posting question on that, the solution is helpful...but not sufficient..
    For ref. the topic is:
    http://forum.java.sun.com/thread.jspa?threadID=606573

  • SAMPLE CODE  + HOW ADD JCOMBOBOX IN JTABLE

    HI,
    ALL OF U
    PLZ SUGGEST ME HOW TO ADD COMBOBOX IN JTABLE.
    AND ALSO TELL HOW WE CAN ADD ITEMS IN COMBOBOX AT RUN TIME.
    PLZ SUGGEST ME.
    THANX IN ADVANCE.
    BYE

    Hi if you google you find a lot
    http://www.google.be/search?q=JTable+combobox&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:nl:official&client=firefox-a
    and
    http://www.google.be/search?q=JTable+combobox+example&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:nl:official&client=firefox-a
    Satanduvel

  • COMBOBOX & CHECKBOX RENDERER IN JTABLE

    Hi,
    I created JXTable by using swingx palette in Netbeans IDE. In two columns of my table, for each row I want to put checkboxes and comboboxes. I searched the ways on internet and I finalise my code. However, because I used cell editor, I just see my checkboxes and comboboxes when I enter a specific cell. I read all tutorials but unfortunately I cannot learn how to use renderer to show comboboxes and checkboxes all the time. In below you could check my code and if possible please teach how to use renderers and try to give feedback to my code by fixing it. Thank you.
    *(P.S Please don't send any web site for tutorial, i searched almost all of them; but I can't understand the logic of it.)*
    // SET UP THE COMBO BOX
    public void setUpOverwriteValueColumn(JXTable table, TableColumn overwriteValCol) {
    valueCombo = new JComboBox();
    Field field = new Field();
    ArrayList values = new ArrayList();
    values = field.getValues();
    for(String a:values){
    valueCombo.addItem(a);
    overwriteValCol.setCellEditor(new DefaultCellEditor(valueCombo));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    overwriteValCol.setCellRenderer(renderer);
    // SET UP THE CHECK BOX
    public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
    valueChk = new JCheckBox();
    overwriteCol.setCellEditor(new DefaultCellEditor(valueChk));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for check box");
    overwriteCol.setCellRenderer(renderer);
    setUpOverwriteColumn(monitorTable, monitorTable.getColumnModel().getColumn(3)); //add checkbox to 3rd column
    setUpOverwriteValueColumn(monitorTable, monitorTable.getColumnModel().getColumn(4)); //add combobox to 4th column

    Finally I can add renderers. But, now I have different question. When user clicks on the checkbox I want to enable the combo box. I mean if user clicks the checkbox in row 3; only the combo box which placed in row 3 should be enabled; other combos in other rows should not be enabled. Please help if you know the answer. Here is my code:
    public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
        public ComboBoxRenderer(Vector items) {
            super(items);
            setOpaque(false);
        public Component getTableCellRendererComponent(
                                                    JTable table,
                                                    Object value,
                                                    boolean isSelected,
                                                    boolean hasFocus,
                                                    int row,
                                                    int column){
            if (isSelected && !hasFocus){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            }else{
                setBackground(table.getBackground());
                setForeground(table.getForeground());
              setSelectedItem(value);
            return this;
    public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer
      public CheckBoxRenderer() {
        setOpaque(false);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
      public Component getTableCellRendererComponent(
                                                        JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
        if (value != null) {
          this.setSelected( ( (Boolean) value).booleanValue());
        return this;
    }To show:
    public void setUpOverwriteValueColumn(JXTable table,
                                     TableColumn overwriteValCol) {
            Vector v = new Vector();
            Field field = new Field();
                ArrayList <String> values = new ArrayList<String>();
                values = field.getValues();
                for(String a:values){
                    v.addElement(a);
                ComboBoxRenderer renderer = new ComboBoxRenderer(v);
                overwriteValCol.setCellRenderer(renderer);
        // SET UP THE CHECK BOX
        public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
                CheckBoxRenderer renderer = new CheckBoxRenderer();
                overwriteCol.setCellRenderer(renderer);
        }Edited by: duygu_simsek on Jun 18, 2009 11:27 AM

  • Combobox Autocomplete editor inside Jtable cell

    I have a custom combobox editor which supports the autocomplete feature as follows:
    as soon as the user keys in any character, this editor searches for the item that starts with keyed in character. This item is displayed in the editor text field and the combobox popup is set to visible and the this item is set to selected.
    this editor works fine when standalone. but the popup fails to become visible when this combobox is used as an celleditor inside jtable. infact the focus is lost from the entire table.
    can anyone suggest the possible reason (and solution if possible).
    following are the code snippets for the same: -
         private TableCellEditor addCellEditor() {
              final JComboBox myJComboBox = new PIComboBox();
              myJComboBox.setModel(new DefaultComboBoxModel(// some data model //));
              //change the size of popup window
              BasicComboPopup comboPopup = null;
              for (int i=0, n=getUI().getAccessibleChildrenCount(myJComboBox); i<n; i++) {
                  Object component = getUI().getAccessibleChild(myJComboBox, i);
                  if (component instanceof BasicComboPopup) {
                   comboPopup = (BasicComboPopup) component;
                   break;
              if(null != comboPopup)
                  comboPopup.setLayout(new GridLayout(1,1));
                  comboPopup.setPopupSize(new Dimension(200, 150));
              myJComboBox.setEditable(true);
              myJComboBox.setEditor(new ComboBoxAutoCompleteEditor(myJComboBox, 3));
              myJComboBox.setUI(new ComboBoxAutoCompleteUI());
              TableCellEditor myCellEditor = new DefaultCellEditor(myJComboBox );
              return myCellEditor;
         public class ComboBoxAutoCompleteEditor extends BasicComboBoxEditor {
         public ComboBoxAutoCompleteEditor(PIComboBox comboBox, int maxLength) {
              super();
              this.comboBox = comboBox;
              this.maxLength = maxLength;
         @Override
         public Component getEditorComponent() {
              if(null == editorComponent)
                   editorComponent = new PITextField();
                   editorComponent.setBorder(null);
                   editorComponent.setMaxLength(maxLength);
                   editorComponent.setDocument(getDocument());
              return editorComponent;
         private ComboBoxAutoCompleteDocument getDocument()
              if(null == comboBoxAutoCompleteDocument)
                   comboBoxAutoCompleteDocument = new ComboBoxAutoCompleteDocument(
                             this.comboBox.getModel());
                   comboBoxAutoCompleteDocument.addDocumentListener(new ComboBoxDocumentListener());
              return comboBoxAutoCompleteDocument;
         private class ComboBoxDocumentListener implements DocumentListener {
              public void insertUpdate(DocumentEvent e) {
                   if (updatingSelection) {
                        return;
                   SwingUtilities.invokeLater(new ScrollHandler());
              public void removeUpdate(DocumentEvent e) {
              public void changedUpdate(DocumentEvent e) {
         private class ScrollHandler implements Runnable {
              private String scrollToString;
              private int scrollToRow;
              private ScrollHandler() {
                   try {
                        int length = getDocument().getLength();
                        String text = getDocument().getText(0, length);
                        scrollToRow = -1;
                        scrollToString = (String) comboBox.getSelectedItem();
                        ComboBoxModel model = comboBox.getModel();
                        int size = model.getSize();
                        for (int i = 0;  i < size; i++) {
                             String item = model.getElementAt(i).toString();
                             if (item.startsWith(text)) {
                                  scrollToString = item;
                                  break;
                             scrollToRow++;
                   } catch (BadLocationException ble) {
                        // TODO: handle
                        ble.printStackTrace();
              public void run() {
                   final int matchCount = getDocument()
                             .getCurrentMatchCount();
                   updatingSelection = true;
                   comboBox.setSelectedItem(scrollToString);
                   if (comboBox.isDisplayable())
                        comboBox.showPopup();
                   updatingSelection = false;
                   if (scrollToRow != comboBox.getItemCount() - 1) {
                        ComboBoxAutoCompleteUI ui = (ComboBoxAutoCompleteUI) comboBox
                                  .getUI();
                        JList popupList = ui.getPopupList();
                        int rowsToAdd = Math.min(comboBox.getMaximumRowCount(), comboBox
                                  .getItemCount()
                                  - scrollToRow - 1);
                        popupList.scrollRectToVisible(popupList.getCellBounds(
                                  scrollToRow + rowsToAdd, scrollToRow + rowsToAdd));
                   if (matchCount > 0) {
                        ((PITextField)getEditorComponent()).setSelectionStart(matchCount);
                        ((PITextField)getEditorComponent()).setSelectionEnd(
                                  getDocument().getLength());
         public class ComboBoxAutoCompleteUI extends BasicComboBoxUI {
             JList getPopupList() {
                 return popup.getList();
         public class ComboBoxAutoCompleteDocument extends PlainDocument {
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            currentMatchCount = getLength() + str.length();
            String currentText = getText(0, getLength());
            //search the matching string here
            offs = 0;
            remove(0, getLength());
            super.insertString(offs, str, a);
         **************

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • Combobox in jtable

    suppose you are editing a combobox in a jtable.
    in the combobox, there are items like
    A0
    A20
    C0
    C20
    E0
    E20
    my main goal is traverse and edit the table by keyboard.
    when i go to a jcombobox, e.g. i hit the button C, it only focus the combo, not selecting item.
    JComboBox comboBox = new JComboBox(arr){
                   protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                        int condition, boolean pressed) {
                    boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
                    if (!retValue && isStartingCellEdit() && editor != null) {
                        //editor.setItem(String.valueOf(ks.getKeyChar()));
                        JComponent editorComponent = (JComponent) getEditor().getEditorComponent();
                        InputMap map = editorComponent.getInputMap(condition);
                        ActionMap am = editorComponent.getActionMap();
                        if(map!=null && am!=null && isEnabled()){
                            Object binding = map.get(ks);
                            Action action = (binding==null) ? null : am.get(binding);
                            if(action!=null){
                                 SwingUtilities.notifyAction(action, ks, e, editorComponent,
                                        e.getModifiers());
                    return retValue;
                private boolean isStartingCellEdit() {
                    JTable table = (JTable) SwingUtilities.getAncestorOfClass(
                            JTable.class, this);
                    return table != null
                            && table.isFocusOwner()
                            && !Boolean.FALSE.equals((Boolean) table
                                    .getClientProperty("JTable.autoStartsEdit"));
    };so if i want to write C20,
    when i pressed C, it selects the combo, so after pressing 2 and 0, it searches for 20.
    how can i do this not to lose the first char?

    suppose you are editing a combobox in a jtable.
    in the combobox, there are items like
    A0
    A20
    C0
    C20
    E0
    E20
    my main goal is traverse and edit the table by keyboard.
    when i go to a jcombobox, e.g. i hit the button C, it only focus the combo, not selecting item.
    JComboBox comboBox = new JComboBox(arr){
                   protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                        int condition, boolean pressed) {
                    boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
                    if (!retValue && isStartingCellEdit() && editor != null) {
                        //editor.setItem(String.valueOf(ks.getKeyChar()));
                        JComponent editorComponent = (JComponent) getEditor().getEditorComponent();
                        InputMap map = editorComponent.getInputMap(condition);
                        ActionMap am = editorComponent.getActionMap();
                        if(map!=null && am!=null && isEnabled()){
                            Object binding = map.get(ks);
                            Action action = (binding==null) ? null : am.get(binding);
                            if(action!=null){
                                 SwingUtilities.notifyAction(action, ks, e, editorComponent,
                                        e.getModifiers());
                    return retValue;
                private boolean isStartingCellEdit() {
                    JTable table = (JTable) SwingUtilities.getAncestorOfClass(
                            JTable.class, this);
                    return table != null
                            && table.isFocusOwner()
                            && !Boolean.FALSE.equals((Boolean) table
                                    .getClientProperty("JTable.autoStartsEdit"));
    };so if i want to write C20,
    when i pressed C, it selects the combo, so after pressing 2 and 0, it searches for 20.
    how can i do this not to lose the first char?

  • Combobox in jtable two tab problem

    Hi all,
    If i am using combobox for one of the columns of jtable with custom editor and renderer, it needs two tab for navigation between the cells.
    How can i make it as 'one tab navigation'. Even i tried with 'isManagingfocus() return true' but...no effect.
    thanx in advance.
    S.A.Radha.

    here I'm giving a simple sample code. Refer this..
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class Class1 extends JFrame {
    JScrollPane jScrollPane1 = new JScrollPane();
    JTable editableTable1 = new JTable(3, 3);     
    public Class1() {
    try {          
    JComboBox c = new JComboBox();
    c.setEditable(true);
    c.addItem("a");
    c.addItem("b");
    DefaultCellEditor cellEditor = new DefaultCellEditor(c);
    TableColumn tc = editableTable1.getColumnModel().getColumn(0);
    tc.setCellEditor(cellEditor);
    this.getContentPane().setLayout(null);
    jScrollPane1.setBounds(new Rectangle(25, 19, 330, 180));
    this.getContentPane().add(jScrollPane1, null);
    jScrollPane1.getViewport().add(editableTable1, null);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    } catch(Exception e) {
    System.out.println("Exception in Class1:"+e);
    public static void main(String[] args) {
    Class1 class1 = new Class1();
    class1.setSize(400, 400);
    class1.setVisible(true);

  • ComboBox size in JTable

    How do you set the size of a combobox inside a JTable cell. I have used setPreferredWidth but the ccombo box is still huge. I have done searches and not found any answers.
    Thanks

    I've always let the UI take care of it. I don't set the minimum, maximum or preferred sizes and the UI sets the size to the size fo the cell.

  • Size of combobox in JTable with custom cell editor

    Hi All -
    I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
    So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
    Eric

    Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
    You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
    Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

  • Combobox Renderer in JTable

    Can someone please post code showing me how to make a renderer that would indicate a combobox in a JTable? I already have the combobox editor there, but I want the renderer to show a small down arrow, indicating to the user that the cell is a combobox.
    Thanks!

    public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
        public ComboBoxRenderer(Vector items) {
            super(items);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
            if (isSelected && !hasFocus){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            }else{
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            setSelectedItem(value);
            return this;
    [/code[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need combobox with a Jtable to view client & server files

    Hellow Everybody,
    I am quite new to Java, although I have experience with other
    programming languages.
    I have searched for tutorials, code, examples etc. but have not found
    much that can help me so far. I am a BCA student & I am appearing for my last year exams. I studied about various Java programs in my course and I decided to make a Swing based FTP Server. Although I not expert in Java , but I have learnt the network programming very much clearly, and that�s why by the help these I wrote a program but it not complete. I have given the program below.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.StringTokenizer;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JProgressBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.EmptyBorder;
    import sun.net.TelnetInputStream;
    import sun.net.ftp.FtpClient;
    public class Client extends JFrame {
    public static int BUFFER_SIZE = 10240;
    protected JTextField userNameTextField = new JTextField("anonymous");
    protected JPasswordField passwordTextField = new JPasswordField(10);
    protected JTextField urlTextField = new JTextField(20);
    protected JTextField fileTextField = new JTextField(10);
    protected JTextArea monitorTextArea = new JTextArea(5, 20);
    protected JProgressBar m_progress = new JProgressBar();
    protected JButton putButton = new JButton("Upload <<");
    protected JButton getButton;
    protected JButton fileButton = new JButton("File");
    protected JButton closeButton = new JButton("Close");
    protected JFileChooser fileChooser = new JFileChooser();
    protected FtpClient ftpClient;
    protected String localFileName;
    protected String remoteFileName;
    public Client() {
    super("FTP Client");
    JPanel p = new JPanel();
    p.setBorder(new EmptyBorder(5, 5, 5, 5));
    p.add(new JLabel("User name:"));
    p.add(userNameTextField);
    p.add(new JLabel("Password:"));
    p.add(passwordTextField);
    p.add(new JLabel("URL:"));
    p.add(urlTextField);
    p.add(new JLabel("File:"));
    p.add(fileTextField);
    monitorTextArea.setEditable(false);
    JScrollPane ps = new JScrollPane(monitorTextArea);
    p.add(ps);
    m_progress.setStringPainted(true);
    m_progress.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.white,
    Color.gray));
    m_progress.setMinimum(0);
    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(m_progress, BorderLayout.CENTER);
    p.add(p1);
    ActionListener lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread uploader = new Thread() {
    public void run() {
    putFile();
    disconnect();
    uploader.start();
    putButton.addActionListener(lst);
    putButton.setMnemonic('U');
    p.add(putButton);
    getButton = new JButton("Download >>");
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (connect()) {
    Thread downloader = new Thread() {
    public void run() {
    getFile();
    disconnect();
    downloader.start();
    getButton.addActionListener(lst);
    getButton.setMnemonic('D');
    p.add(getButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (fileChooser.showSaveDialog(Client.this) != JFileChooser.APPROVE_OPTION)
    return;
    File f = fileChooser.getSelectedFile();
    fileTextField.setText(f.getPath());
    fileButton.addActionListener(lst);
    fileButton.setMnemonic('f');
    p.add(fileButton);
    lst = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (ftpClient != null)
    disconnect();
    else
    System.exit(0);
    closeButton.addActionListener(lst);
    closeButton.setDefaultCapable(true);
    closeButton.setMnemonic('g');
    p.add(closeButton);
    getContentPane().add(p, BorderLayout.CENTER);
    fileChooser.setCurrentDirectory(new File("."));
    fileChooser
    .setApproveButtonToolTipText("Select file for upload/download");
    WindowListener wndCloser = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    disconnect();
    System.exit(0);
    addWindowListener(wndCloser);
    setSize(720, 240);
    setVisible(true);
    public void setButtonStates(boolean state) {
    putButton.setEnabled(state);
    getButton.setEnabled(state);
    fileButton.setEnabled(state);
    protected boolean connect() {
    monitorTextArea.setText("");
    setButtonStates(false);
    closeButton.setText("Cancel");
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    String user = userNameTextField.getText();
    if (user.length() == 0) {
    setMessage("Please enter user name");
    setButtonStates(true);
    return false;
    String password = new String(passwordTextField.getPassword());
    String sUrl = urlTextField.getText();
    if (sUrl.length() == 0) {
    setMessage("Please enter URL");
    setButtonStates(true);
    return false;
    localFileName = fileTextField.getText();
    // Parse URL
    int index = sUrl.indexOf("//");
    if (index >= 0)
    sUrl = sUrl.substring(index + 2);
    index = sUrl.indexOf("/");
    String host = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    String sDir = "";
    index = sUrl.lastIndexOf("/");
    if (index >= 0) {
    sDir = sUrl.substring(0, index);
    sUrl = sUrl.substring(index + 1);
    remoteFileName = sUrl;
    try {
    setMessage("Connecting to host " + host);
    ftpClient = new FtpClient(host);
    ftpClient.login(user, password);
    setMessage("User " + user + " login OK");
    setMessage(ftpClient.welcomeMsg);
    ftpClient.cd(sDir);
    setMessage("Directory: " + sDir);
    ftpClient.binary();
    return true;
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    setButtonStates(true);
    return false;
    protected void disconnect() {
    if (ftpClient != null) {
    try {
    ftpClient.closeServer();
    } catch (IOException ex) {
    ftpClient = null;
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(0);
    putButton.setEnabled(true);
    getButton.setEnabled(true);
    fileButton.setEnabled(true);
    closeButton.setText("Close");
    Client.this.setCursor(Cursor
    .getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    SwingUtilities.invokeLater(runner);
    protected void getFile() {
    if (localFileName.length() == 0) {
    localFileName = remoteFileName;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    fileTextField.setText(localFileName);
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    int size = getFileSize(ftpClient, remoteFileName);
    if (size > 0) {
    setMessage("File " + remoteFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    } else
    setMessage("File " + remoteFileName + ": size unknown");
    FileOutputStream out = new FileOutputStream(localFileName);
    InputStream in = ftpClient.get(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    if (size > 0) {
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    } else {
    int kb = counter / 1024;
    setProgressString(kb + " KB");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void putFile() {
    if (localFileName.length() == 0) {
    setMessage("Please enter file name");
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
    File f = new File(localFileName);
    int size = (int) f.length();
    setMessage("File " + localFileName + ": " + size + " bytes");
    setProgressMaximum(size);
    FileInputStream in = new FileInputStream(localFileName);
    OutputStream out = ftpClient.put(remoteFileName);
    int counter = 0;
    while (true) {
    int bytes = in.read(buffer);
    if (bytes < 0)
    break;
    out.write(buffer, 0, bytes);
    counter += bytes;
    setProgressValue(counter);
    int proc = (int) Math
    .round(m_progress.getPercentComplete() * 100);
    setProgressString(proc + " %");
    out.close();
    in.close();
    } catch (Exception ex) {
    setMessage("Error: " + ex.toString());
    protected void setMessage(final String str) {
    if (str != null) {
    Runnable runner = new Runnable() {
    public void run() {
    monitorTextArea.append(str + '\n');
    monitorTextArea.repaint();
    SwingUtilities.invokeLater(runner);
    protected void setProgressValue(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setValue(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressMaximum(final int value) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setMaximum(value);
    SwingUtilities.invokeLater(runner);
    protected void setProgressString(final String string) {
    Runnable runner = new Runnable() {
    public void run() {
    m_progress.setString(string);
    SwingUtilities.invokeLater(runner);
    public static int getFileSize(FtpClient client, String fileName)
    throws IOException {
    TelnetInputStream lst = client.list();
    String str = "";
    fileName = fileName.toLowerCase();
    while (true) {
    int c = lst.read();
    char ch = (char) c;
    if (c < 0 || ch == '\n') {
    str = str.toLowerCase();
    if (str.indexOf(fileName) >= 0) {
    StringTokenizer tk = new StringTokenizer(str);
    int index = 0;
    while (tk.hasMoreTokens()) {
    String token = tk.nextToken();
    if (index == 4)
    try {
    return Integer.parseInt(token);
    } catch (NumberFormatException ex) {
    return -1;
    index++;
    str = "";
    if (c <= 0)
    break;
    str += ch;
    return -1;
    public static void main(String argv[]) {
    new Client();
    The above given code is not yet complete. I want some specific features to be implemented in this code that is given below.
    1.     A login Gridlayout or Borderlayout & within it the username & password textfield.
    2.     When the username and password will request to server and if it will success then the textfields of the username & password have to be disable.
    3 . Two Combobox. One will give client directories and files and another
    will give the server directories and files.
    4 . Below the Combobox two JTable will be given & the tables wll show the
    client and server directories and files.
    Could anybody give me the codes that I want. If anybody check this code please help me????
    With Regards,
    DILLU

    Well Mr Michael_Dunn,
    Thanks for responding my query. First of all I would like to tell that
    this FTP server is going to be my project and that's why I am submmiting my question. I told in my points that I want a Jcombobox & a JTable for displaying that files & directories. whenever I set the directories in the combobox the files will be displayed in the JTable
    I hope you understand my point

  • Editable Combobox in a JTable

    Hi All,
    I have a editable combobox in a normal JTable as one of columns.Can any body help me to set the size to the entered text in editable combobox. Means if I set the length to 5 then it should accpet only 5 characters.so how to achive it ??
    Regards
    Suresh

    First get cell editor that should be a combobox. Then get its editor that should be text box and then set its size.

  • Combobox in JTable question

    Hello,
    I have to make a button in a JTable that is activated with a right button and then like in a combobox appears a menue and every item in this menue should be activated with the left button and perform some action. Like in windows right click and then select smth.
    My question is should I do it with Combobox and if yes how to activate it with the right button because it always listens to left button. It is implemented with action listener and I tried mouse listener but it wouldn"t listen to that. I will be glad to any solutions.
    Thanx,
    Miroslav

    Hi,
    And thank you for the answer. i think I will use jpop menu as u sujested(Thank you for that). Now I should only see how to make the render and the editor to put it in a cell in a JTable.
    It should be activated with the right button, beacause my task is such and because I also think that it is better this way. II mean it is more natural than with the left button.
    Miroslav

Maybe you are looking for

  • I am getting error from keyword not found where expected

    I am unable to find the error in the following query... its giving from key word not found where expected select ms.state_name,sum(decode(mp.status,'12',1,0)) cnt_active,sum(decode( mp.status,'12',mh.chargesheet_name,0)) sum_active, sum(decode(mp.sta

  • Logging correct user name when creating users

    I wrote a function that creates users through a portlet in version 3.0.9.8.4 It works fine except for logging who created the user. The schema where the functions and procedures are used gets updated in the wwsec_person$.created_by_dbuser field. The

  • Converting problems with QT file!

    I have a few Quicktime MOV files that I want to send a friend who owns a PC. The problem is - he gets audio but NO video (black screen) when he tries to play or convert these files with any of his software. I tried to convert the file on my Mac using

  • Bpc : problem with batch logic setting

    Hi,   I am using bpc 7.0 MS version 7.0.112.   i am trying to run a customized DM package. in test6.lgf, i have the following codes (thanks to Tim): *SELECT(%UsersChoiceTimeID%,[TimeID],[TIME],"[ID]='%TIME_SET%'") *SELECT(%UsersChoiceYEAR%,[Year],[TI

  • New i5 MacBook Pro won't read or play certain DVD's

    Just got a new i5 MBP and it won't read certain DVD's that I put in. It tries to read them but then spits them back out after a few seconds. Any thoughts?