JComboBox setSlectedItem

I have JComboBox.setSelectedItem("foo");
Using this information , I want to get the index of this selected Item. How do I get index? ex If "foo" is at index 2:
JComboBox.getSelectedIndex should return 2.
thnx

Hi
if you need to get the index just after you selected the value, just use JComboBox#getSelectedIndex()if your JComboBox use a DefaultComboBoxModel, you can use DefaultComboBoxModel#getIndexOf()have a look there
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
Nico

Similar Messages

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • JComboBox causing GTK-WARNING and GTK-CRITICAL on Ubuntu 8.04

    I was wondering why whenever I use the GTK Look and Feel, my JComboBox's cause GTK issues. They also don't display right...
    Here is the code I am using....
    import javax.swing.*;
    public class ComboBoxDisplayTest extends JFrame
      public ComboBoxDisplayTest()
        try
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
          SwingUtilities.updateComponentTreeUI(this);
        catch(Exception ex)
          ex.printStackTrace();
        JComboBox cb = new JComboBox();
        this.add(cb);
        cb.addItem("Item 1");
        cb.addItem("Item 2");
      public static void main(String[] args)
        ComboBoxDisplayTest c = new ComboBoxDisplayTest();
        c.pack();
        c.setVisible(true);
    }This is what get's printed onto the terminal when I run the program:
    java ComboBoxDisplayTest
    (<unknown>:7078): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:7078): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failedWhat exactly is going on?
    Is there something wrong with my code?
    Is there any way to fix this?
    Any answers are much appreciated...
    Thanks

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6624717
    as far as i know (i am using Ubuntu 7.10 & OpenJDK 1.6.0_0-b11 & Sun JDK) not fixed yet ....
    Ronald

  • Associate Action with jcombobox item

    Is it possible to associate a particular Action with a jcombobox item (for example using setAction()). When the user selects a particular item of jcombobox, the Action must be triggered.
    regards,
    Nirvan.

    Hi,
    You can associate a particular action with a JComboBox. As per my understanding u can add one action perfrom action to combobox or itemStateChanged action
    if u add action perform action, u need to add the following method to ur logic.
    JComboBox combobox=new JComboBox();
        combobox.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
             JComboBox combo = (JComboBox)evt.getSource();
                if(combo.getSelectedItem().equals("LOCATION")) {
                A a = new A();
                a.show();
            } else if(combo.getSelectedItem().equals("HOUSE")) {
                B b= new B();
                b.show();
            });if action is ItemStateChanged then add the following method.
    combobox.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    and write your logic here which one needs to be triggered when this action performed.
            });Hope this will help to you....
    Thanks & Regards,
    Maadhav..

  • Retrieving values from a JComboBox - Design question.

    I would like some design guidance on a problem that I am hoping has been solved before. Here is my situation:
    I have a JComboBox that I populate with String values from a database table. The exact set of values to be loaded into the JComboBox varies according values specified elsewhere on the GUI.
    When I select an item from the JComboBox, I need to read the database to retrieve more information. The text is not sufficient for me to identify the data I need, so I need to get the table key from somewhere.
    Is there anyway I can associate my table key with the text value inside the JComboBox and retrieve it when the user selects a drop down value from the JComboBox?
    Many thanks in advance.

    when you load the data from the db, try to get ALL the information needed: item label+item value+description. put this data into a map (a hashmap) for example using a unique identifier. For example, use a numeric index. In this case, the item value should be the index that uniquely identifies your items.
    create a simple bean that encapsulates the item contents: index+value+label, description.
    Doing this will avoid the huge db access occurences.
    hth

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Problem with JComboBox in a JPanel

    I have a JComboBox in a JPanel (with a gridbaglayout), and I add items to the combobox:
    String[] stateList={"AL",.....};
    JCombobox stateCB=new JComboBox(stateList);
    and when I run the application, the states appear in the box, but when I click on the box, there is no drop-down list!
    any ideas?

    Is the combobox Enabled if it is then after adding it to anything set it to true cause i poersonally tried out as u have given it it works and else if it does not show a list then use the setmodel function and set the model to DefaultComboBoxModel and then add the items using a for loop

  • Problem with JComboBox in a fixed JToolBar

    Hi,
    I've created a JComboBox in a JToolBar that contains all available fonts. When I click on the drop down arrow I only see the first font and a small part of the second. The JComboBox is dropped down in fact just as far as the border of the JToolbar. All the rest isn't visible to me; it seems that they are behind the other components of my JApplet. However, if I move the JToolBar from it's position (as it's a floatable component), there's no problem at all. So I'm wondering why I can't see everything when the JToolBar is docked.... Can anyone help me?
    Thanks in advance!!
    E_J

    it seems that they are behind the other components of my JApplet.Sounds like you are mixing AWT components with your Swing application. Make sure you are using JPanel, JButton ... and not Panel, Button....

  • Problem with JComboBox in aTable Cell

    I try to put JComboBox in JTableCell,
    what i want to do is something like this...
    Question | Answer |
    1. what is your favourite | a. Pizza |
    food? | b. Hot Dog |
    2. what is your favourite | a. red |
    color? | b. blue |
    Object[][] data = {
    {"1.What is your favourite food?", new AnswerChoices(new String[]{"a.Pizza","b.Hot Dog"})},
    {"2.What is your favourite color?", new AnswerChoices(new String[]{"a.red","b.blue"})}
    here my code;
    //class AnswerChoicesCellEditor
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    import de.falcom.table.*;
    public class AnswerChoicesCellEditor extends AbstractCellEditor implements TableCellEditor{
         protected JComboBox mComboBox;
    public AnswerChoicesCellEditor(){
         mComboBox = new JComboBox();
         mComboBox.addActionListener(this);
         mComboBox.setEditable(false);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){
         if(value instanceof AnswerChoices){
              AnswerChoices a = (AnswerChoices)value;
              String[] c = a.getChoices();
              mComboBox.removeAllItems();
              for(int i=0; i < c.length; i++)
                   mComboBox.addItem(c);
                   mComboBox.setSelectedIndex(a.getAnswer());
         return mComboBox;
    public Object getCellEditorValue(){
         int nchoices = mComboBox.getItemCount();
         String[] c = new String[nchoices];
         for(int i = 0; i<nchoices; i++){
              c[i] = mComboBox.getItemAt(i).toString();
         return new AnswerChoices(c,mComboBox.getSelectedIndex());
         //return mComboBox.getSelectedItem(); //here i get but after selection there is no comboBox in tableCell
    //the Renderer class
    import javax.swing.table.TableCellRenderer;
    import javax.swing.*;
    import java.awt.Component;
    public class AnswerChoicesCellRenderer extends JComboBox implements TableCellRenderer {
         private Object curValue;
    /** Creates new AnswerChoiceCellRenderer */
    public AnswerChoicesCellRenderer() {
    setEditable(false);
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
    if (value instanceof AnswerChoices) {
    AnswerChoices nl = (AnswerChoices)value;
    String[] tList = nl.getChoices();
    if (tList != null) {
    removeAllItems();
    for (int i=0; i<tList.length; i++)
    addItem(tList[i]);
         setSelectedIndex(AnswerChoices.getAnswer());
         //this.setSelectedItem();
    //return this;
    //this.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (table != null)
    if (table.isCellEditable(row, column))
    setForeground(CellRendererConstants.EDITABLE_COLOR);
    else
    setForeground(CellRendererConstants.UNEDITABLE_COLOR);
              setBackground(table.getBackground());
    return this;
    public class AnswerChoices {
         static int ans = 0;
         String[] choices ;
    public AnswerChoices(String[]c,int a){
              choices = c;
              ans          = a;
    public AnswerChoices(String[] c){
              this(c,0);
    public String[] getChoices(){
         return choices;
    public void setAnswer(int a){
         ans = a;
    public static int getAnswer(){
         return ans;
    //the TableModel i used in my app
    import java.awt.Color;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    import javax.swing.*;
    public class FAL_Table extends JTable {
    /** Creates new FAL_Table */
    public FAL_Table(DefaultTableModel dtm) {
    super(dtm);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setBackground(java.awt.Color.white);
    setDefaultCellEditorRenderer();
    private void setDefaultCellEditorRenderer(Class forClass, TableCellEditor editor, TableCellRenderer renderer) {
         setDefaultEditor(forClass, editor);
         setDefaultRenderer(forClass, renderer);
         private void setDefaultCellEditorRenderer() {
              // Setting default editor&renderer of Boolean
              setDefaultCellEditorRenderer(Boolean.class, new BooleanCellEditor(), new BooleanCellRenderer());
              //Setting default editor&renderer of ComboBox
              setDefaultCellEditorRenderer(JComboBox.class, new ComboBoxCellEditor( ),new ComboBoxRenderer());
              // Number class
              // Setting default editor&renderer of java.math.BigDecimal
              setDefaultCellEditorRenderer(java.math.BigDecimal.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.math.BigInteger
              setDefaultCellEditorRenderer(java.math.BigInteger.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.lang.Byte
              setDefaultCellEditorRenderer(Byte.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Double
              setDefaultCellEditorRenderer(Double.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Float
              setDefaultCellEditorRenderer(Float.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Integer
              setDefaultCellEditorRenderer(Integer.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Long
              setDefaultCellEditorRenderer(Long.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Short
              setDefaultCellEditorRenderer(Short.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of String
              setDefaultCellEditorRenderer(String.class,new StringCellEditor(), new StringCellRenderer());
              // Setting default editor&renderer of FileName
              setDefaultCellEditorRenderer(FileName.class,new FileNameCellEditor(), new FileNameCellRenderer());
              // Setting default editor&renderer of Color
              setDefaultCellEditorRenderer(Color.class,new ColorCellEditor(), new ColorCellRenderer());
              setDefaultCellEditorRenderer(AnswerChoices.class, new AnswerChoicesCellEditor(), new AnswerChoicesCellRenderer());
              setDefaultCellEditorRenderer(JSpinner.class, new SpinnerCellEditor(), new SpinnerRenderer());
    public Class getCellClass(int row,int col) {
    TableModel model = getModel();
    if (model instanceof FAL_TableModel) {
    FAL_TableModel ptm = (FAL_TableModel)model;
    return ptm.getCellClass(row,convertColumnIndexToModel(col));
    return model.getColumnClass(convertColumnIndexToModel(col));
    public TableCellRenderer getCellRenderer(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellRenderer renderer = tableColumn.getCellRenderer();
    if (renderer == null) {
    renderer = getDefaultRenderer(getCellClass(row,column));
    return renderer;
    public TableCellEditor getCellEditor(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellEditor editor = tableColumn.getCellEditor();
    if (editor == null) {
    editor = getDefaultEditor(getCellClass(row,column));
    return editor;
    import javax.swing.table.*;
    import java.util.Vector;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    public class FAL_TableModel extends DefaultTableModel implements TableModel {
    public FAL_TableModel() {
    this((Vector)null, 0);
    public FAL_TableModel(int numRows, int numColumns) {
    super(numRows,numColumns);
    public FAL_TableModel(Vector columnNames, int numRows) {
    super(columnNames,numRows);
    public FAL_TableModel(Object[] columnNames, int numRows) {
    super(convertToVector(columnNames), numRows);
    public FAL_TableModel(Vector data, Vector columnNames) {
    setDataVector(data, columnNames);
    public FAL_TableModel(Object[][] data, Object[] columnNames) {
    setDataVector(data, columnNames);
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    Object obj = getValueAt(row,col);
    if (col != 1){
    return false;
         }else{
              return true;
    public Class getCellClass(int row,int col) {
    Object obj = getValueAt(row,col);
    if (obj != null)
         return obj.getClass();
         else
         return Object.class;
    public Object getCellValue(int row,int col) {
    Object obj = getValueAt(row,col);
              return obj;      
    my problem is, when i select an item from one of the comboBox in the table the value of the other cells changes too and i have the same problem with JSpinner.
    please help i am stuck
    Gebi

    and when i try to get the current value oa a cell it returns the Component class like this
    AnswerChoices@bf1f20 ...

  • JComboBox.setPopupVisible() and focus

    Hello,
    the following code demonstrates that always when the combobox is editable and the standard focus sequence is modified, a setPopupVisible(true) indeed opens the popup, but it is immediately closed again. Is anything wrong with the code?
    Although there are quite a number of JComboBox bugs in the database, I did not find this one. If it is a bug, of course I would be interested in a workaround.
    Regards
    J�rg
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Y extends JFrame
      private JComboBox cmb;
      public Y()
      { setSize(300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container cp= getContentPane();
        cp.setLayout(null);
        final JCheckBox cb= new JCheckBox("Combo editable");
        cb.setBounds(80,30,130,20);
        cb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
         cmb.setEditable(cb.isSelected());
        final JTextField tf1= new JTextField();
        tf1.setBounds(50,60,60,20);
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         if (!tf1.getText().equals("ee")) {
           cmb.requestFocusInWindow(); // Prevents popup to stay open.
           cmb.setPopupVisible(true);
           System.out.println(cmb.isVisible());
        JTextField tf2= new JTextField();
        tf2.setBounds(150,60,60,20);
        tf2.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         cmb.setPopupVisible(true);
        cmb = new JComboBox(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"});
        cmb.setBounds(100,90,50,20);
        cmb.setSelectedIndex(-1);
        System.out.println("LightWeight: "+cmb.isLightWeightPopupEnabled());
        cp.add(cb);
        cp.add(tf1);
        cp.add(tf2);
        cp.add(cmb);
        setVisible(true);
        tf1.requestFocusInWindow();
      public static void main(String args[])
      { java.awt.EventQueue.invokeLater(new Runnable()
        { public void run()
          { new Y();
    }

    Well, there's two things I note. The first is you're printing out the comboBox's visible status, which is always true, when you're probably trying to get the comboBox's popup's visible status.
    The second thing is the cause of your problem. You request focus on the combo box. When it is editable, however, it is the editor component that gets the focus, not the combo box. So, the popup is made visible and then the editor component loses focus because the combo box gets focus, and so the popup is hidden.
    This change does what you want, I think:
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
        if (!tf1.getText().equals("ee")) {
            if ( cmb.isEditable() )
                cmb.getEditor().getEditorComponent().requestFocusInWindow();
            else
                cmb.requestFocusInWindow(); // Prevents popup to stay open.
          cmb.setPopupVisible(true);
          System.out.println(cmb.isVisible());
        });

  • JComboBox popup list remains open after losing keyboard focus

    Hi,
    I have noticed a strange JComboBox behavior. When you click on the drop down arrow to show the popup list, and then press the Tab key, the keyboard focus moves to the next focusable component, but the popup list remains visible.
    I have included a program that demonstrates the behavior. Run the program, click the drop down arrow, then press the Tab key. The cursor will move into the JTextField but the combo box's popup list is still visible.
    Does anyone know how I can change this???
    Thanks for any help or ideas.
    --Yeath
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends JFrame
       public Test()
          super( "Test Application" );
          this.getContentPane().setLayout( new BorderLayout() );
          Box box = Box.createHorizontalBox();
          this.getContentPane().add( box, BorderLayout.CENTER );
          Vector<String> vector = new Vector<String>();
          vector.add( "Item" );
          vector.add( "Another Item" );
          vector.add( "Yet Another Item" );
          JComboBox jcb = new JComboBox( vector );
          jcb.setEditable( true );
          JTextField jtf = new JTextField( 10 );
          box.add( jcb );
          box.add( jtf );
       public static void main( String[] args )
          Test test = new Test();
          test.pack();
          test.setVisible( true );
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    ran your code on 1.5.0_3, observed problem as stated.
    even though the cursor is merrily blinking in the textfield, you have to click into
    the textfield to dispose the dropdown
    ran your code on 1.4.2_08, no problems at all - tabbing into textfield immediately
    disposed the dropdown
    another example of 'usual' behaviour (involving focus) breaking between 1.4 and 1.5
    the problem is that any workaround now, may itself be broken in future versions

  • JTable with JComboBox

    Hi friends,
    I am adding JComboBox in JTable its working properly
    But data is not adding dynamically to JComboBox
    I am Sending my Code plz give me reply
    I am Struggleing from 1 week on wards
    package com.dnt.autopopulation;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.event.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.TableModelEvent;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;
    import java.text.SimpleDateFormat;
    import java.util.Vector;
    import javax.swing.border.*;
    import com.dnt.eaip.Connectmagr;
    import com.dnt.eaip.*;
    import com.dnt.util.*;
    import javax.swing.plaf.ButtonUI;
    import com.dnt.admin.EndStartDateCheck;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    public class AutoPopRollBack extends JPanel {
    boolean selection = false;
    public static final int HAND_CURSOR = 12;
    Cursor cursor = new Cursor(HAND_CURSOR);
    int selectedRow = -1;
    ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
    JLabel HeaderLabe = new JLabel(headertop1);
    Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
    Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
    new Color(154, 254, 211), new Color(108, 178, 148),
    new Color(37, 60, 50), new Color(53, 87, 72));
    DefaultTableModel dm = new DefaultTableModel();
    Vector searchlist = new Vector();
    Vector rows = new Vector();
    Vector returnList;
    Connectmagr objConnectmagr = new Connectmagr();
    JFrame frame = new JFrame();
    JLabel headlab = new JLabel();
    JCalendarComboBox EndDateTxt;
    JLabel HawbLab = new JLabel();
    JTextField HawbTxt = new JTextField();
    JLabel AgentLab = new JLabel();
    JLabel StartDateLab = new JLabel();
    JCalendarComboBox StartDateTxt;
    JComboBox AgentLBox = new JComboBox();
    JLabel EnddateLab = new JLabel();
    JPanel ReviewJobsPane = new JPanel();
    JButton SearchBtn = new JButton();
    ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
    ArrayList AgentList = new ArrayList();
    JComboBox DocTypeLBox = new JComboBox();
    JLabel doctypelab = new JLabel();
    JPanel displayPanel = new JPanel();
    ButtonGroup group1;
    JRadioButton rb;
    JTable table;
    public ArrayList jobList = new ArrayList();
    public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
    this.frame = frame;
    this.AgentList = agentArrayList;
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public void jbInit() throws Exception {
    Calendar cal = Calendar.getInstance();
    Locale loc = new Locale("");
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    HeaderLabe.setBackground(new Color(250, 233, 216));
    HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
    this.setLayout(null);
    this.setBackground(SystemColor.control);
    headlab.setBackground(new Color(250, 233, 216));
    headlab.setFont(new java.awt.Font("Verdana", 1, 12));
    headlab.setForeground(Color.blue);
    headlab.setHorizontalAlignment(SwingConstants.CENTER);
    headlab.setText(" :: Auto Population Rollback");
    headlab.setBounds(new Rectangle(39, 2, 247, 25));
    EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
    EndDateTxt.setBackground(Color.white);
    EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EndDateTxt.setForeground(Color.blue);
    EndDateTxt.setBorder(null);
    HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
    HawbLab.setForeground(Color.blue);
    HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
    HawbLab.setText("Job No/Airway Bill No:");
    HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
    HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
    HawbTxt.setText("");
    HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    HawbTxt.setForeground(Color.blue);
    HawbTxt.setBorder(border1);
    AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
    AgentLab.setForeground(Color.blue);
    AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
    AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
    AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
    StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    StartDateLab.setForeground(Color.blue);
    StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    StartDateLab.setText("Start Date:");
    StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
    StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
    StartDateTxt.setBackground(Color.white);
    StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    StartDateTxt.setForeground(Color.blue);
    StartDateTxt.setBorder(null);
    AgentLBox.setBackground(Color.white);
    AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    AgentLBox.setForeground(Color.blue);
    AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
    AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    EnddateLab.setForeground(Color.blue);
    EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    EnddateLab.setText("End Date:");
    EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
    ReviewJobsPane.setBackground(new Color(240, 233, 216));
    ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
    ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
    ReviewJobsPane.setLayout(null);
    SearchBtn.setUI(ui);
    SearchBtn.setCursor(cursor);
    SearchBtn.setBackground(new Color(76, 125, 104));
    SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
    SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
    SearchBtn.setForeground(Color.white);
    SearchBtn.setBorder(border2);
    SearchBtn.setOpaque(true);
    SearchBtn.setFocusPainted(false);
    SearchBtn.setText("Search");
    SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
    for (int i = 0; i < AgentList.size(); i++)
    AgentLBox.addItem( (String) AgentList.get(i));
    DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    DocTypeLBox.setForeground(Color.blue);
    DocTypeLBox.setMinimumSize(new Dimension(22, 19));
    DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
    DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    DocTypeLBox.addItem("New Jobs");
    DocTypeLBox.addItem("Draft jobs");
    DocTypeLBox.addItem("Finished jobs");
    doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
    doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
    doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
    doctypelab.setForeground(Color.blue);
    doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
    displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
    this.add(headlab, null);
    this.add(HeaderLabe, null);
    this.add(ReviewJobsPane, null);
    ReviewJobsPane.add(HawbLab, null);
    ReviewJobsPane.add(AgentLab, null);
    ReviewJobsPane.add(AgentLBox, null);
    ReviewJobsPane.add(StartDateLab, null);
    ReviewJobsPane.add(StartDateTxt, null);
    ReviewJobsPane.add(HawbTxt, null);
    ReviewJobsPane.add(EnddateLab, null);
    ReviewJobsPane.add(EndDateTxt, null);
    ReviewJobsPane.add(DocTypeLBox, null);
    ReviewJobsPane.add(doctypelab, null);
    this.add(SearchBtn, null);
    this.add(displayPanel, null);
    //this.add(scrollPaneView, null);
    // scrollPaneView.getViewport().add(displayPanel, null);
    this.setVisible(true);
    void FieldEditable(boolean str) {
    StartDateTxt.setEnabled(str);
    EndDateTxt.setEnabled(str);
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    ArrayList agentlist = new ArrayList();
    agentlist.add(0, "BF0651");
    agentlist.add(1, "PF0010");
    AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
    frame.getContentPane().add(objAutoPopRollBack);
    frame.setBounds(new Rectangle(0, 0, 820, 593));
    frame.setVisible(true);
    void SearchBtn_actionPerformed(ActionEvent e) {
    displayPanel.setVisible(false);
    Vector data=new Vector();
    rows.removeAllElements();
    boolean flag = true;
    String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
    try {
    if(HawbTxt.getText().equalsIgnoreCase("")){
    if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(this, "Please Select Start Date",
    "Warning", JOptionPane.WARNING_MESSAGE);
    flag = false;
    else if (!che.equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
    flag = false;
    }else{
    FieldEditable(true);
    if (flag) {
    try {
    displayPanel.removeAll();
    } catch (Exception ex) {
    rows.removeAllElements();
    data.removeAllElements();
    SearchBtn.setEnabled(true);
    searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
    if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
    searchlist.add(1, HawbTxt.getText().toString().trim());
    else
    searchlist.add(1, "");
    searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
    String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
    String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
    Vector columns = new Vector();
    columns.add(0, "");
    columns.add(1, "JOB No");
    columns.add(2, "Status");
    columns.add(3, "Current Form Type");
    columns.add(4, "New Form Type");
    System.out.println("Before calling Data Base");
    jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
    if (jobList.size() > 0) {
    for (int i = 0; i < jobList.size(); i++) {
    ArrayList temp = new ArrayList();
    temp = (ArrayList) jobList.get(i);
    Vector col = new Vector();
    col.add(0, new Boolean(false));
    col.add(1, temp.get(0).toString().trim());
    col.add(2, temp.get(1).toString().trim());
    col.add(3, temp.get(2).toString().trim());
    Vector tempstr=new Vector();
    String [] tem=temp.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    col.add(4, new JComboBox(tempstr));
    data.add(col);
    dm.setDataVector(data, columns);
    table = new JTable(dm) {
    public void tableChanged(TableModelEvent e) {
    super.tableChanged(e);
    public boolean isCellEditable(int rowIndex, int vColIndex) {
    return true;
    JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(false);
    table.setBackground(SystemColor.inactiveCaptionText);
    table.setRowHeight(20);
    JTableHeader head = table.getTableHeader();
    head.setSize(850, 75);
    table.setTableHeader(head);
    table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
    table.getTableHeader().setBackground(new Color(130, 170, 150));
    table.getTableHeader().setForeground(Color.BLUE);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
    table.setForeground(new Color(125, 25, 0));
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setMinWidth(75);
    col.setMaxWidth(75);
    TableColumn col1 = table.getColumnModel().getColumn(1);
    col1.setMinWidth(150);
    col1.setMaxWidth(150);
    TableColumn col2 = table.getColumnModel().getColumn(2);
    col2.setMinWidth(150);
    col2.setMaxWidth(150);
    TableColumn col3 = table.getColumnModel().getColumn(3);
    col3.setMinWidth(150);
    col3.setMaxWidth(150);
    TableColumn col4 = table.getColumnModel().getColumn(4);
    col4.setMinWidth(160);
    col4.setMaxWidth(160);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
    Vector tempstr=new Vector();
    for(int j=0;j<jobList.size();j++){
    ArrayList temlist=(ArrayList)jobList.get(j);
    String [] tem=temlist.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    JComboBox portTypesCombo = new JComboBox(tempstr);
    col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
    col4 = table.getColumnModel().getColumn(4);
    col4.setCellEditor(new MyComboBoxEditor(tempstr));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
    System.out.println(tempstr);
    displayPanel.setLayout(new BorderLayout());
    displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    table.setEditingColumn(0);
    int column = 0;
    if (e.getClickCount() == 1) {
    Point p = e.getPoint();
    selectedRow = table.rowAtPoint(p);
    column = table.columnAtPoint(p);
    System.out.println(table.isCellEditable(selectedRow, column));
    if (column != 0) {
    selectedRow = -1;
    returnList = new Vector();
    returnList = (Vector) rows.get(selectedRow);
    else if (column == 0) {
    table.revalidate();
    table.repaint();
    scroll.getViewport().add(table);
    displayPanel.add(scroll, BorderLayout.CENTER);
    displayPanel.setVisible(true);
    else {
    JOptionPane.showMessageDialog(this, "No Data Available");
    } catch (Exception e1) {
    e1.printStackTrace();
    class MyItemListener implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if (source instanceof AbstractButton == false)return;
    boolean checked = e.getStateChange() == ItemEvent.SELECTED;
    for (int x = 0, y = table.getRowCount(); x < y; x++) {
    table.setValueAt(new Boolean(checked), x, 0);
    class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
    AutoPopRollBack adaptee;
    AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.SearchBtn_actionPerformed(e);
    class RadioButtonRenderer implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value == null)return null;
    return (Component) value;
    class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
    private JRadioButton button;
    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row,
    int column) {
    if (value == null)return null;
    button = (JRadioButton) value;
    button.addItemListener(this);
    return (Component) value;
    public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
    protected static Border m_noFocusBorder;
    public CheckCellRenderer() {
    super();
    m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(m_noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (value instanceof Boolean) {
    Boolean b = (Boolean) value;
    setSelected(b.booleanValue());
    setBackground(isSelected && !hasFocus ?
    table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected && !hasFocus ?
    table.getSelectionForeground() : table.getForeground());
    setFont(table.getFont());
    setBorder(hasFocus ? UIManager.getBorder(
    "Table.focusCellHighlightBorder") : m_noFocusBorder);
    return this;
    class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
    protected CheckBoxHeader rendererComponent;
    protected int column;
    protected boolean mousePressed = false;
    public CheckBoxHeader(ItemListener itemListener) {
    rendererComponent = this;
    rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    rendererComponent.setForeground(header.getForeground());
    rendererComponent.setBackground(header.getBackground());
    rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
    header.addMouseListener(rendererComponent);
    setColumn(column);
    rendererComponent.setText("Select All");
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return rendererComponent;
    protected void setColumn(int column) {
    this.column = column;
    public int getColumn() {
    return column;
    protected void handleClickEvent(MouseEvent e) {
    if (mousePressed) {
    mousePressed = false;
    JTableHeader header = (JTableHeader) (e.getSource());
    JTable tableView = header.getTable();
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
    doClick();
    public void mouseClicked(MouseEvent e) {
    handleClickEvent(e);
    ( (JTableHeader) e.getSource()).repaint();
    public void mousePressed(MouseEvent e) {
    mousePressed = true;
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector 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;
    class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    and Bringing data from data base by using this method
    if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
    else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
    st = con.createStatement();
    System.out.println("---new jobs search-->" + sqlString);
    rs = st.executeQuery(sqlString);
    while (rs.next()) {
    retVector = new ArrayList();
    retVector.add(0, rs.getString("JOBNO"));
    retVector.add(1, "New Job");
    retVector.add(2, rs.getString("DOC_TYPE"));
    String temp="";
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    temp="K8I|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
    temp="K8E";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
    // temp="K1|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
    temp="K1|K8I";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
    temp="K2";
    retVector.add(3,temp);
    retVector.add(3, rs.getString("AGENT_CODE"));
    retVectorlist.add(retVector);
    i am sending data To ComboBox like this
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    K8I and K8T
    if K2 adding k8E and for other types as mentioned above
    But for ComboBoxes it is showing same Items not changing
    Please any body can help to me
    Thanks and Regards
    Ravichandra

    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • Imageicon in a JComboBox

    hi, i do a program to create "business case table", but i've a problem in the 2nd part of the table, because in my 2nd table i have a JComboBox with image, when i click the combobox the images are show, but when select some figure the cell don�t keep the image, only keep the text.
    Anyone can help me???
    Here is my principal class that create the principal screen and tables:
    /*                      Poseidon                                 */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Summary description for Poseidon
    *2052102
    public class Poseidon extends JFrame
         // Variables declaration
         private JTabbedPane jTabbedPane1;
         private JPanel contentPane, paineltabela, painelgrafo, painelvariavel, paineltarefa;
         private JTable tabelavariavel,tabelatarefa, tabelateste;
         private JScrollPane scrollvariavel, scrolltarefa;
         private int totallinhas, alt, al, linhastarefa,cont, linhas, tamanholinhas,
                        controlalinhas, index, contastring;
         private String variavel;
         private JComboBox combobox;
         JMenuItem sair, abrir, guardar, miadtarefa, miadvariavel;
         JTable [] tabelasvar = new JTable[30];
         JFrame w;
         // End of variables declaration
         public Poseidon()
              super("Poseidon");
              initializeComponent();
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              JMenuBar barra = new JMenuBar();
              setJMenuBar(barra);
              TratBarra trat = new TratBarra();
              tabelavariavel = new JTable();
              tabelatarefa = new JTable();
              tabelavariavel.getTableHeader().setReorderingAllowed(false);
              tabelavariavel.setModel(new DefaultTableModel());
              tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
              tabelavariavel.setBackground(Color.cyan);
              tabelatarefa.getTableHeader().setReorderingAllowed(false);
              tabelatarefa.setModel(new DefaultTableModel());
              tabelatarefa.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tabelatarefa.setBackground(Color.white);
              CaixaCombinacao combobox = new CaixaCombinacao();
              DefaultCellEditor editor = new DefaultCellEditor(combobox);
              tabelatarefa.setDefaultEditor(Object.class, editor);
              painelvariavel = new JPanel();
              painelvariavel.setLayout(new GridLayout(1, 0));
              painelvariavel.setBorder(new TitledBorder("Variaveis"));
              painelvariavel.setBounds(15, 35, 490, 650);
              painelvariavel.setVisible(false);
              this.add(painelvariavel);
              scrollvariavel = new JScrollPane();
              scrollvariavel.setViewportView(tabelavariavel);
              painelvariavel.add(scrollvariavel);
              paineltarefa = new JPanel();
              paineltarefa.setLayout(new GridLayout(1,0));
              paineltarefa.setBorder(new TitledBorder("Tarefas"));
              paineltarefa.setBounds(506, 35, 490,650);
              paineltarefa.setVisible(false);
              this.add(paineltarefa);
              scrolltarefa = new JScrollPane();
              scrolltarefa.setViewportView(tabelatarefa);
              paineltarefa.add(scrolltarefa);
              tamanholinhas = 1;
              linhas=1;
              cont=0;
              JMenu arquivo = new JMenu("Arquivo");
              JMenu mtabela = new JMenu("Tabela");
              arquivo.setMnemonic(KeyEvent.VK_A);
              mtabela.setMnemonic(KeyEvent.VK_T);
              miadvariavel = new JMenuItem("Adicionar Variavel");
              miadtarefa = new JMenuItem("Adicionar Tarefa");
              abrir = new JMenuItem("Abrir");
              guardar = new JMenuItem("Guardar");
              sair = new JMenuItem("Sair");
              sair.addActionListener(trat);
              miadvariavel.addActionListener(trat);
              miadtarefa.addActionListener(trat);
              mtabela.add(miadvariavel);
              miadvariavel.setMnemonic(KeyEvent.VK_V);
              mtabela.add(miadtarefa);
              miadtarefa.setMnemonic(KeyEvent.VK_F);
              arquivo.add(abrir);
              abrir.setMnemonic(KeyEvent.VK_B);
              arquivo.add(guardar);
              guardar.setMnemonic(KeyEvent.VK_G);
              arquivo.addSeparator();
              arquivo.add(sair);
              sair.setMnemonic(KeyEvent.VK_S);
              barra.add(arquivo);
              barra.add(mtabela);
              jTabbedPane1 = new JTabbedPane();
              contentPane = (JPanel)this.getContentPane();
              paineltabela = new JPanel();
              painelgrafo = new JPanel();
              // jTabbedPane1
              jTabbedPane1.addTab("Tabela", paineltabela);
              jTabbedPane1.addTab("Grafo", painelgrafo);
              jTabbedPane1.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e)
                        painelvariavel.setVisible(false);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jTabbedPane1, 11,10,990,690);
              // paineltabela
              paineltabela.setLayout(null);
              // painelgrafo
              painelgrafo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
              // Poseidon
              this.setTitle("UMa Poseidon");
              this.setLocation(new Point(2, 1));
              this.setSize(new Dimension(558, 441));
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setExtendedState(MAXIMIZED_BOTH);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTabbedPane1_stateChanged(ChangeEvent e)
              System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
              // TODO: Add any handling code here
         // TODO: Add any method code to meet your needs in the following area
         private class TratBarra implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   if(e.getSource() == sair){
                        int op = JOptionPane.showConfirmDialog(null, "Deseja mesmo fechar o aplicativo?","Sair", JOptionPane.YES_NO_OPTION);
                        if(op == JOptionPane.YES_OPTION){
                             System.exit(0);
                   if(e.getSource() == miadvariavel){
                        final JFrame w = new JFrame();
                        new AdVariavel(w);
                   if(e.getSource() == miadtarefa){
                        final JFrame w = new JFrame();
                        new AdTarefa(w);
    //============================= Testing ================================//
    //=                                                                    =//
    //= The following main method is just for testing this class you built.=//
    //= After testing,you may simply delete it.                            =//
    //======================================================================//
         public static void main(String[] args)
              Spash sp = new Spash(3000);
              sp.mostraTela();
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              new Poseidon();
    //= End of Testing =
    private class AdVariavel extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton varOK;
         private JButton varCancel;
         private JPanel contentPane;
         private JTextField jTextField2;
         private JList listadominio;
         private JScrollPane jScrollPane1;
         private JButton varAdiciona;
         private JButton varRemove;
         private JPanel jPanel1;
         private DefaultListModel modelo1;
         // End of variables declaration
         public AdVariavel(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              modelo1 = new DefaultListModel();
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              varOK = new JButton();
              varCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              jTextField2 = new JTextField();
              listadominio = new JList(modelo1);
              jScrollPane1 = new JScrollPane();
              varAdiciona = new JButton();
              varRemove = new JButton();
              jPanel1 = new JPanel();
              // jLabel1
              jLabel1.setText("Nome da vari�vel:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // varOK
              varOK.setText("OK");
              varOK.setMnemonic(KeyEvent.VK_O);
              varOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varOK_actionPerformed(e);
              // varCancel
              varCancel.setText("Cancelar");
              varCancel.setMnemonic(KeyEvent.VK_C);
              varCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,137,22);
              addComponent(contentPane, varOK, 170,227,83,28);
              addComponent(contentPane, varCancel, 257,227,85,28);
              addComponent(contentPane, jPanel1, 12,42,332,180);
              // jTextField2
              jTextField2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField2_actionPerformed(e);
              // listadominio
              listadominio.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e)
                        listadominio_valueChanged(e);
              // jScrollPane1
              jScrollPane1.setViewportView(listadominio);
              // varAdiciona
              varAdiciona.setText("Adicionar");
              varAdiciona.setMnemonic(KeyEvent.VK_A);
              varAdiciona.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varAdiciona_actionPerformed(e);
              // varRemove
              varRemove.setText("Remover");
              varRemove.setMnemonic(KeyEvent.VK_R);
              varRemove.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varRemove_actionPerformed(e);
              // jPanel1
              jPanel1.setLayout(null);
              jPanel1.setBorder(new TitledBorder("Dominio:"));
              addComponent(jPanel1, jTextField2, 17,22,130,22);
              addComponent(jPanel1, jScrollPane1, 165,21,154,144);
              addComponent(jPanel1, varAdiciona, 56,50,89,28);
              addComponent(jPanel1, varRemove, 57,84,88,28);
              // AdTarefas
              this.setTitle("Adicionar Variavel");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(367, 296));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void varOK_actionPerformed(ActionEvent e)
              System.out.println("\nvarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma variavel","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else {
                   if (modelo1.getSize() == 0){
                        JOptionPane.showMessageDialog(null,"N�o introduziu nenhum dominio","AVISO", 1 );
                        return;
                   else{
                        painelvariavel.add(scrollvariavel);
                        index = 0;
                        variavel = jTextField1.getText();
                        contastring = variavel.length();
                        System.out.println(contastring);
                        DefaultTableModel dtm = (DefaultTableModel)tabelavariavel.getModel();
                        tabelavariavel.getTableHeader().setBackground(Color.yellow);
                        dtm.addColumn(variavel, new Object[]{});
                        al = modelo1.getSize();
                        totallinhas = al;
                        for(int i = 0;i < modelo1.getSize();i++){
                             listadominio.setSelectedIndex(index) ;
                             Object dominio = listadominio.getSelectedValue();
                             dtm.addRow(new Object[]{dominio});
                             index ++;
                        tabelasvar[cont] = tabelavariavel;
                        cont++;
                        System.out.println(cont);
                        for(int i=0;i<cont;i++){
                             tabelateste = tabelasvar;
                             linhas = tabelateste.getRowCount();
                             if (linhas >= tamanholinhas){
                                  tamanholinhas = linhas;
                        for (int i=0;i<cont;i++){
                             tabelateste = tabelasvar[i];
                             System.out.println(linhas);
                             linhas = tabelateste.getRowCount();
                             tabelateste.setRowHeight((tamanholinhas/linhas)*20);
                             tabelasvar[i] = tabelateste;
                             System.out.println(tabelateste);
                   tabelavariavel = new JTable();
              scrollvariavel = new JScrollPane();
              painelvariavel.add(tabelavariavel);
              tabelavariavel.setBackground(Color.cyan);
         tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                   scrollvariavel.setViewportView(tabelavariavel);
                   painelvariavel.setVisible(true);
         tabelavariavel.getTableHeader().setReorderingAllowed(false);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
              // TODO: Add any handling code here
         private void varCancel_actionPerformed(ActionEvent e)
              System.out.println("\nvarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
         private void jTextField2_actionPerformed(ActionEvent e)
              System.out.println("\njTextField2_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void listadominio_valueChanged(ListSelectionEvent e)
              System.out.println("\nlistadominio_valueChanged(ListSelectionEvent e) called.");
              if(!e.getValueIsAdjusting())
                   Object o = listadominio.getSelectedValue();
                   System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
                   // TODO: Add any handling code here for the particular object being selected
         private void varAdiciona_actionPerformed(ActionEvent e)
              System.out.println("\nvarAdiciona_actionPerformed(ActionEvent e) called.");
              if(jTextField2.getText().length()>=1){
                   modelo1.addElement(jTextField2.getText());
                   jTextField2.setText("");
                   jTextField2.requestFocus();
         private void varRemove_actionPerformed(ActionEvent e)
              System.out.println("\nvarRemove_actionPerformed(ActionEvent e) called.");
              int index = listadominio.getSelectedIndex();
              modelo1.remove(index);
         // TODO: Add any method code to meet your needs in the following area
    private class AdTarefa extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton tarOK;
         private JButton tarCancel;
         private JPanel contentPane;
         private JPanel jPanel1;
         // End of variables declaration
         public AdTarefa(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always regenerated
         * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
         * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
         * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              tarOK = new JButton();
              tarCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // jLabel1
              jLabel1.setText("Nome da tarefa:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // tarOK
              tarOK.setText("OK");
              tarOK.setMnemonic(KeyEvent.VK_O);
              tarOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarOK_actionPerformed(e);
              // tarCancel
              tarCancel.setText("Cancelar");
              tarCancel.setMnemonic(KeyEvent.VK_C);
              tarCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,120,22);
              addComponent(contentPane, tarOK, 10,50,83,28);
              addComponent(contentPane, tarCancel, 153,50,85,28);
              // AdTarefas
              this.setTitle("Adicionar Tarefa");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(250, 120));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void tarOK_actionPerformed(ActionEvent e)
              System.out.println("\ntarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma tarefa","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else{
                   String variavel = jTextField1.getText();
                   DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   dtm.addColumn(variavel,new Object[]{});
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   for(int i=0; i < tabelatarefa.getColumnCount(); i++){
                        tabelatarefa.getColumnModel().getColumn(i).setPreferredWidth(100);
                   tabelatarefa.getColumnModel().getColumn(i).setResizable(false);
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
                   paineltarefa.setVisible(true);
         tabelatarefa.getTableHeader().setReorderingAllowed(true);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         // TODO: Add any handling code here
         private void tarCancel_actionPerformed(ActionEvent e)
              System.out.println("\ntarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
    now the code to create the JComboBox is here:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CaixaCombinacao extends JComboBox{
         ImageIcon[] imagens;
        String[] op = {"x", "check"};
    public CaixaCombinacao(){
         imagens = new ImageIcon[op.length];
        Integer[] intArray = new Integer[op.length];
        for (int i = 0; i < op.length; i++) {
             intArray[i] = new Integer(i);
            imagens[i] = createImageIcon("imagens/" + op[i] + ".gif");
            this.addItem(imagens);
    if (imagens[i] != null) {
    imagens[i].setDescription(op[i]);
         JComboBox lista = new JComboBox(intArray);
         ComboBoxRenderer renderer= new ComboBoxRenderer();
         lista.setRenderer(renderer);
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CaixaCombinacao.class.getResource(path);
    if (imgURL != null) {
         return new ImageIcon(imgURL);
    return null;
    class ComboBoxRenderer extends JLabel
    implements ListCellRenderer {
    public ComboBoxRenderer() {
    setOpaque(true);
    setHorizontalAlignment(CENTER);
    setVerticalAlignment(CENTER);
    public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus) {
                   int selectedIndex = ((Integer)value).intValue();
                   if (isSelected) {
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    } else {
    setBackground(list.getBackground());
    setForeground(list.getForeground());
                   ImageIcon icon = imagens[selectedIndex];
                   String opc = op[selectedIndex];
    setIcon(icon);
    return this;

    I'm sure 90% of the code posted here has nothing to do with displaying images in a JTable.
    Here is an example that shows how to display an icon in a table:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("copy16.gif"), "Copy"},
                   {new ImageIcon("add16.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }If this doesn't help then post a similiar demo program that shows the problems you are having, not your entire application.

  • Animated gifs in JComboBox

    I am trying to put animated gifs into a JComboBox and having some problems. Inside the list they get updated, but when the list is closed the one does not get updated. Here is the code for my custom ComboBox
    public class PresetComboBox extends JComboBox
         Preset[] m_presets;
         public PresetComboBox(Preset[] preset)
              super(presets);
              m_presets = presets;
              setRenderer(new PresetListCellRenderer());
         private class PresetListCellRenderer extends JLabel implements ListCellRenderer
              public Component getListCellRendererComponent(JList list, Object value, int index,
                                                                          boolean isSelected, boolean cellHasFocus)
                   Preset preset = (Preset)value;
                   //set the list as the image observer, so that the animated gifs get updated
                   preset.getIcon().setImageObserver(list);
                   setText(preset.getDesc());
                   setIcon(preset.getIcon());
                   //make sure the selected item looks selected and the non selected ones dont
                   if (isSelected)
                        setBackground(list.getSelectionBackground());
                        setForeground(list.getSelectionForeground());
                   else
                        setBackground(list.getBackground());
                        setForeground(list.getForeground());
                   return this;

    One simple way is:
    label.setText("<html><img src=.....></html>");

  • JComboBox takes ages to load/refresh when tried to add more items.

    Swing gurus ...
    Here is the test app generated from VA3.5 concept is the
    same - JComboBox takes long time to add data items to itself when added more items.
    In this senario, I tried to load about 500 items into the combo box, takes about 2+ minutes to load. I have an app which needs to show about 1K items in the pick list ( ComboBox ) - which takes any where from 4 - 10 min - this is not acceptable - are there any ways we can load more items into combo box ? Help is really appreciated.
    Example:
    * Insert the type's description here.
    * Creation date: (6/28/2001 11:23:26 AM)
    * @author: Administrator
    public class ComboTest extends javax.swing.JFrame {
         private javax.swing.JPanel ivjJFrameContentPane = null;
         private javax.swing.JButton ivjLoadBtn = null;
         private javax.swing.JComboBox ivjTestCombo = null;
    * ComboTest constructor comment.
    public ComboTest() {
         super();
         initialize();
    * ComboTest constructor comment.
    * @param title java.lang.String
    public ComboTest(String title) {
         super(title);
    * connEtoC1: (LoadBtn.action.actionPerformed(java.awt.event.ActionEvent) --> ComboTest.loadBtn_ActionPerformed(Ljava.awt.event.ActionEvent;)V)
    * @param arg1 java.awt.event.ActionEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.ActionEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.loadBtn_ActionPerformed(arg1);
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the JFrameContentPane property value.
    * @return javax.swing.JPanel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JPanel getJFrameContentPane() {
         if (ivjJFrameContentPane == null) {
              try {
                   ivjJFrameContentPane = new javax.swing.JPanel();
                   ivjJFrameContentPane.setName("JFrameContentPane");
                   ivjJFrameContentPane.setLayout(null);
                   getJFrameContentPane().add(getTestCombo(), getTestCombo().getName());
                   getJFrameContentPane().add(getLoadBtn(), getLoadBtn().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjJFrameContentPane;
    * Return the LoadBtn property value.
    * @return javax.swing.JButton
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JButton getLoadBtn() {
         if (ivjLoadBtn == null) {
              try {
                   ivjLoadBtn = new javax.swing.JButton();
                   ivjLoadBtn.setName("LoadBtn");
                   ivjLoadBtn.setText("Load");
                   ivjLoadBtn.setBounds(248, 41, 85, 25);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjLoadBtn;
    * Return the TestCombo property value.
    * @return javax.swing.JComboBox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JComboBox getTestCombo() {
         if (ivjTestCombo == null) {
              try {
                   ivjTestCombo = new javax.swing.JComboBox();
                   ivjTestCombo.setName("TestCombo");
                   ivjTestCombo.setDoubleBuffered(true);
                   ivjTestCombo.setBounds(78, 41, 164, 23);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjTestCombo;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         getLoadBtn().addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   connEtoC1(e);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("ComboTest");
              setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
              setSize(426, 131);
              setTitle("Test App");
              setContentPane(getJFrameContentPane());
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Comment
    public void loadBtn_ActionPerformed(java.awt.event.ActionEvent actionEvent)
         String val = "String Item: ";
         for ( int i=0; i<500; i++ )
              getTestCombo().addItem( val + i);
         return;
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              ComboTest aComboTest;
              aComboTest = new ComboTest();
              aComboTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aComboTest.show();
              java.awt.Insets insets = aComboTest.getInsets();
              aComboTest.setSize(aComboTest.getWidth() + insets.left + insets.right, aComboTest.getHeight() + insets.top + insets.bottom);
              aComboTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of javax.swing.JFrame");
              exception.printStackTrace(System.out);

    The "Really fast combo boxes" thread referred to by lk555 can be summarized as follows:
    1. RegFish wrote a custom JComboBox that handles large numbers of elements better than a standard JComboBox does.
    2. You can download his code at http://www.reddfish.co.nz/freesoftware/PoliteComboBox.jar
    3. You may want to reconsider your design, since a JComboBox with more than a few dozen elements is usually too hard for the user to use (see various postings in the long thread).

Maybe you are looking for

  • Creation of project, Project ID any number ranges are there?

    Creation of project, Project ID any number ranges are there?

  • Wich HDMI-cable I need for the iMac?

    I allready have the adapter Thunderbolt to HDMI. I want to connect a beamer (Panasonic PT-AX200E). In the beamer-manual stands: "Required is a cable, wich is compatible for the HDMI 1.080p signal (RP-CDHG100: optional)". Yours faithfully

  • Maintenance Order creation control

    Is there a way to control that a Maintenance Order could be created only if the notification is already put in progress? Not if the notification is on status u201COutstanding notificationu201D. Iu2019ve tried to do it by security access but didnu2019

  • How to Host completed Captivate Content

    I thought completed Captivate 5 Content could be hosted on Acrobat.com.  I see how to upload and share content for reviews.  I have attempted to upload a project and all that I see will upload is a zip and pdf file but not cptx.  I thought the option

  • CS3 improvements ...

    Can anyone tell me if there have been any improvments to the code view in CS3? Examples: - a "Functions" panel for PHP, etc... - Some way of connecting up my code to php.net for reference (so I can right-click a php function and bring up the php.net