ListCellRenderer with JComboBox

Hi,
I tried to implement a custom ListCellRenderer for a JComboBox:
public class StatusComboBoxRenderer implements ListCellRenderer {
     JLabel label;
     public StatusComboBoxRenderer() {
          super();
          this.label= new JLabel();
     public Component getListCellRendererComponent(
          JList list,
          Object value,
          int index,
          boolean isSelected,
          boolean cellHasFocus) {
          if (value != null){
                         label.setText(((Status)value).getStatus());
          return this.label;
}Now, at first it seems to work. Each entry is displayed correctly. But when I select an entrie, nothing is shown anymore. The functionality still is correct, the entry is selected. But the ComboBox doesn't display the entries anymore.
What could I have done wrong? Should I use something different than a label? It is just Text that is displayed.
And a second problem: I have to test for (value != null). That happens very often. Is this normal or does this seem to be a problem?
Marco

Hello,
i cant reproduce your problems, perhaps something with your Status class ?
If you want your label to show the selection(background) you have to set it opaque.
import javax.swing.*;
import java.awt.*;
public class StatusComboBoxRenderer implements ListCellRenderer {
     JLabel label;
     public StatusComboBoxRenderer() {
          super();
          this.label= new JLabel();
          this.label.setOpaque(true);
     public Component getListCellRendererComponent(
          JList list,
          Object value,
          int index,
          boolean isSelected,
          boolean cellHasFocus) {
          label.setText((String)value);
          if (isSelected) {
               label.setBackground(list.getSelectionBackground());
               label.setForeground(list.getSelectionForeground());
          } else {
               label.setBackground(list.getBackground());
               label.setForeground(list.getForeground());
          return this.label;
     public static void main(String[]args){
          JComboBox box=new JComboBox(new String[]{"A","B","C"});
          box.setRenderer(new StatusComboBoxRenderer());
          JFrame f =new JFrame();
          JPanel p=new JPanel();
          p.add(box);
          f.setBounds(0,0,200,200);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.getContentPane().add(p);
          f.setVisible(true);
}Sun Tutorial: http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#renderer
Regards,
Tim

Similar Messages

  • FocusListener problem with JComboBox

    Hi,
    I am facing a problem with JComboBox. When I make it as Editable it is not Listening to the FocucListener Event....
    Please tell me if there is any way to overcome this..
    Regards,
    Chandan Sharma

    I searched the forum using "jcombobox focuslistener editable" and quess what, the first posting I read had the solution.
    Search the forum before posting questions.

  • Strange problem with JComboBox

    I am having a strange problem with JComboBox, I created a method as a JComboBox factory which returns a JComboBox filled with items. the method works fine and I can see the items in the JComboBox. The problem is when I try using the method myCombo.SelectedItem(String item); the object myCombo does not set the selected item, it just leaves the item blank (or unselected).
    //This method build a JComboBox
    public javax.swing.JComboBox makeJComboBox(String[] items) {
    javax.swing.JComboBox myComboBox = new javax.swing.JComboBox();
    for (int index=0;index<items.length;index++){
    myComboBox.addItem(makeObj(items[index]));
    return myComboBox;
    public Object makeObj(final String item) {
    return new Object() {
    public String toString() {
    return item;
    }

    Couple of better ways to populate a combo with items-
    public javax.swing.JComboBox makeJComboBox(String[]items) {
    javax.swing.ComboBoxModel cbModel = new DefaultComboBoxModel(items);
    javax.swing.JComboBox myComboBox = new javax.swing.JComboBox(cbModel);
    return myComboBox;
    }OR
    public javax.swing.JComboBox makeJComboBox(String[]items) {
    return new javax.swing.JComboBox(items);

  • 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..

  • 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 ...

  • Need image to update with JComboBox selection

    hello, i have code here that loads an image from a JFileChooser dialog when "Add Image" is clicked, the images name and path is stored in a JComboBox, and the image name is displayed. As more images are added to the JComboBox, I would like to be able to have the picture displayed in concurrence with whatever image is selected from the comboBox. For instance, if Jessica.jpg is selected in the JComboBox, i need Jessica.jpg to be loaded into imagePanel. Here is the code. The problem lies within the JComboBox's "itemStateChanged" I believe... This is what must be used (i think) to update the pictures in the imagePanel when the combobox is manipulated....
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.border.*;
    import java.awt.image.BufferedImage;
    public class MyDialog extends JDialog implements ActionListener, WindowListener, ItemListener
         ReminderClass dataRec;
         ReminderClass originalDataRec;
         Image im;
         MediaTracker mt;
         Toolkit tk;
         JFileChooser imageDialog;
         File f;
         String[] comboBoxList;
         String fileName;
         String filePathName;
         DataManager dataManager;
         JPanel mainPanel1;
         JPanel mainPanel2;
         JPanel mainPanel3;
         JPanel buttonPanel;
         JPanel radioPanel;
         MyImageJPanel imagePanel;
         JScrollPane scrollPane1;
         JScrollPane scrollPane2;
         JRadioButton pendingButton;
         JRadioButton documentationButton;
         JRadioButton completedButton;
         JRadioButton failedButton;
         JRadioButton cancelledButton;
         ButtonGroup radioGroup;
         JComboBox imageComboBox;
         JComboBox category;
         JTextArea description;
         JTextArea message;
         JLabel descriptionLabel;
         JLabel messageLabel;
         JLabel fileNameLabel;
         JLabel categoryLabel;
         JLabel selectedFile;
         GregorianCalendar dueDateTime;
         GregorianCalendar reminderInterval;
         GregorianCalendar terminatedDateTime;
         JButton saveCont;
         JButton cancel;
         JButton addImage;
         JButton saveExit;
         JLabel dueDate;
         JLabel intervalDate;
         JLabel terminatedDate;
         JTextField dueDateField;
         JTextField intervalDateField;
         JTextField terminatedDateField;
         int choice;
         int newIndex;
         public MyDialog(DataManager aDataManager)
         {//add new Reminder to list d-box
              Container cp;
              dataManager = aDataManager;
              dataRec = new ReminderClass();
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              saveCont.setActionCommand("SAVECONT");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameAdd();
         public MyDialog(int index, DataManager aDataManager, ReminderClass newDataRec)
         {//edit an existing reminder dialog
              Container cp;
              dataManager = aDataManager;
              index = newIndex;
              dataRec = newDataRec;
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              dataRec.populateComboBox(imageComboBox);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              fillInData(dataRec);
              saveCont.setActionCommand("SAVECONT2");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT2");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL2");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameEdit();
         void setupMainFrameAdd()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Reminder Add New");
              setVisible(true);
         }//end of setupMainFrame
         void setupMainFrameEdit()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Edit Existing Reminder");
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              JOptionPane optionPane;
              String temp = new String();
              if (e.getActionCommand().equals("CANCEL"))
                   if(dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit without first saving data?","Are you sure you wish to\n" + "exit without first saving data?", JOptionPane.YES_NO_OPTION);
                        if(choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             for (int n = 0; n<imageComboBox.getItemCount(); n++)
                                  dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                             dataRec.setCategory(category.getSelectedIndex());
                             dataManager.add(dataRec);
                             fillInData(dataRec);
                             dispose();
                   else
                        dispose();
              else if (e.getActionCommand().equals("CANCEL2"))
                   if (dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to\n" + "exit without first saving data?");
                        if (choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             this.dispose();
              else if (e.getActionCommand().equals("ADDIMAGE"))
                   filePathName = new String();
                   fileName = new String();
                   imageDialog = new JFileChooser();
                   imageDialog.showOpenDialog(this);
                   f = imageDialog.getSelectedFile();
                   tk = Toolkit.getDefaultToolkit();
                   fileName = f.getName();
                   filePathName = f.getPath();
                   im = tk.getImage(filePathName);
                   try
                        mt = new MediaTracker(this);
                        mt.addImage(im, 432);
                        mt.waitForAll();
                   catch(InterruptedException ie)
                        ie.getStackTrace();
                   imageComboBox.addItem(fileName);
                   dataRec.setImageFileName(fileName);
                   imageComboBox.setSelectedItem(fileName);
                   imagePanel.refreshImage(im , 50, 50);
              else if (e.getActionCommand().equals("SAVECONT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   temp = dueDateField.getText();
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add((ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);     
              else if (e.getActionCommand().equals("SAVECONT2"))
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex,(ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);
              else if (e.getActionCommand().equals("SAVEEXIT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add(dataRec);
                   fillInData(dataRec);
                   dispose();
                   //save new data to list, and exit back to main prog.
              else if (e.getActionCommand().equals("SAVEEXIT2"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex, (ReminderClass)(dataRec.clone()));
                   fillInData(dataRec);
                   dispose();
              else if (e.getActionCommand().equals("PENDING"))
                   dataRec.setStatus("Pending");
              else if (e.getActionCommand().equals("DOCUMENTATION"))
                   dataRec.setStatus("Documentation");
              else if (e.getActionCommand().equals("COMPLETED"))
                   dataRec.setStatus("Completed");
              else if (e.getActionCommand().equals("FAILED"))
                   dataRec.setStatus("Failed");
              else if (e.getActionCommand().equals("CANCELLED"))
                   dataRec.setStatus("Cancelled");
         public void itemStateChanged(ItemEvent e)
               JComboBox cb = (JComboBox)e.getSource();
               int categorySelection;
               if(cb == category)
                 categorySelection = cb.getSelectedIndex();
               if (cb == imageComboBox)
                       tk = Toolkit.getDefaultToolkit();
                        fileName = dataRec.getImageFileName();
                        filePathName = f.getPath();
                        im = tk.getImage(filePathName);
                        try
                             mt = new MediaTracker(this);
                             mt.waitForAll();
                             mt.addImage(im, 432);
                             imagePanel.refreshImage(im , 50, 50);
                        catch(InterruptedException ie)
                        ie.getStackTrace();
         public void fillInData(ReminderClass d)
              fileNameLabel.setText(d.getImageFileName());
              description.setText(d.getDescription());
              message.setText(d.getMessage());
              category.setSelectedIndex(d.getCategory());
         public void windowOpened(WindowEvent e)
              //no action to take
         public void windowClosing(WindowEvent e)
              JOptionPane j = new JOptionPane("Are you sure you wish to exit \n" + "without saving data first?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);;
         public void windowClosed(WindowEvent e)
    //          no action to take
         public void windowIconified(WindowEvent e)
    //          no action to take
         public void windowDeiconified(WindowEvent e)
    //          no action to take
         public void windowActivated(WindowEvent e)
    //          no action to take
         public void windowDeactivated(WindowEvent e)
    //          no action to take
    }Here is the main "ReminderClass" with all methods and accessors/mutators....
    import java.util.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    //search for Java Thumb Wheel under Google.
    public class ReminderClass extends Object implements Cloneable, Comparable
          private int category;
          private String description;
          private String message;
          private GregorianCalendar dueDateTime;
         private GregorianCalendar reminderInterval;
          private GregorianCalendar terminatedDateTime;
          private int displayStyle;
          private int compareKey;
          private String status;
          String[] imagePathArray;
          String[] imageArray;
          String imageFileName;
          int numImages;
          public final static int CATEGORY_FIELD = 1;
          public final static int DESCRIPTION_FIELD = 2;
          public final static int MESSAGE_FIELD = 3;
          public final static int DUE_DATE_TIME_FIELD = 4;
          public final static int REMINDER_INTERVAL_FIELD =5;
          public final static int TERMINATED_DATE_TIME_FIELD = 6;
          public final static int DISPLAY_STYLE_FIELD = 7;
          public final static int COMPARE_KEY_FIELD = 8;
          public final static int STATUS_FIELD = 9;
          static boolean showDescription = false;
          static boolean showDate = false;
          static boolean showCategory = false;
          static boolean showMessage = false;
          static boolean showDueDateTime = false;
          static boolean showReminderInterval = false;
          static boolean showTerminatedDateTime = false;
          static boolean showImageName = false;
          static boolean showStatus = false;
          //******************REMINDER CLASS DEFAULT CONSTRUCTOR***************
          ReminderClass()
               numImages = 0;
               imageArray = new String[20];
               imagePathArray = new String[20];
               imageFileName = "";
               category = -1;
               description = "";
               message = "";
               dueDateTime = new GregorianCalendar();
               reminderInterval = new GregorianCalendar();
               terminatedDateTime = new GregorianCalendar();
               displayStyle = -1;
               compareKey = -1;
         //     *****************REMINDER CLASS INITIALIZER CONSTRUCTOR*************
          ReminderClass(int initCategory, String initDescription, GregorianCalendar initDueDateTime, String[] initImagePathArray, String[] initImageArray, String initImageFileName,
                    GregorianCalendar initReminderInterval, GregorianCalendar initTerminatedDateTime, String initMessage, String initStatus,
                     int initCompareKey, int initDisplayStyle)
               imagePathArray = new String[20];
               imageArray = new String[20];
               for (int n = 0; n<initImageArray.length; n++)
                    imageArray[n] = initImageArray[n];
               for (int n = 0; n<initImagePathArray.length; n++)
                    imagePathArray[n] = initImagePathArray[n];
                    imageFileName = initImageFileName;
                     category = initCategory;
                     description = initDescription;
                     dueDateTime = (GregorianCalendar)initDueDateTime.clone();
                     reminderInterval = (GregorianCalendar)initReminderInterval.clone();
                     terminatedDateTime = (GregorianCalendar)initTerminatedDateTime.clone();
                     message = initMessage;
                     status = initStatus;
                     compareKey = initCompareKey;
                     displayStyle = initDisplayStyle;
               //*********************LOAD DATA FROM FILE WITH CONSTRUCTOR*****************************
            public ReminderClass(DataInputStream dataInStream) throws IOException
                           imageFileName = dataInStream.readUTF();
                       category = dataInStream.readInt();
                       description = dataInStream.readUTF();
                       message = dataInStream.readUTF();
                       dueDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       reminderInterval = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt()); 
                       terminatedDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       displayStyle = dataInStream.readInt();
                       compareKey = dataInStream.readInt();
                       status = dataInStream.readUTF();
             //********************SAVE DATA TO FILE***************************
             public void write(DataOutputStream dataOutStream) throws IOException
                       dataOutStream.writeUTF(imageFileName);
                       dataOutStream.writeInt(category);
                       dataOutStream.writeUTF(description);
                       dataOutStream.writeUTF(message);
                       dataOutStream.writeInt(dueDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.SECOND));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.YEAR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.HOUR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MINUTE));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.SECOND));         
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.SECOND));        
                       dataOutStream.writeInt(displayStyle);
                       dataOutStream.writeInt(compareKey);
                       //dataOutStream.writeUTF(status);
             public void clearFields()
                   numImages = 0;
                   imageFileName = "";
                   category = -1;
                    description = "";
                    message = "";
                    dueDateTime = new GregorianCalendar();
                    reminderInterval = new GregorianCalendar();
                    terminatedDateTime = new GregorianCalendar();
                    displayStyle = -1;
                    status = "";
                    compareKey = -1;
               //************* OVERRIDE clone METHOD***********************
               public Object clone() 
                         ReminderClass c = new ReminderClass();
                         try
                              c = ((ReminderClass)super.clone());
                              c.setImageArray(imageArray);
                              c.setImagePathArray(imagePathArray);
                              c.imageFileName = (String)imageFileName;
                              c.category = (int)category;
                              c.description = (String)description;
                              c.message = (String)message;
                              c.status = (String)status;
                              c.compareKey = (int)compareKey;
                              c.displayStyle = (int)displayStyle;
                              c.dueDateTime = (GregorianCalendar)(dueDateTime.clone());
                              c.reminderInterval = (GregorianCalendar)(reminderInterval.clone());
                              c.terminatedDateTime = (GregorianCalendar)(terminatedDateTime.clone());
                         catch (CloneNotSupportedException e)
                              System.out.println("Fatal Error: " + e.getMessage());
                              System.exit(1);
                         return c;
          //**************** OVERRIDE toString METHOD*************************
          public String toString()
               String s = new String();
               s =  description;
              if (showCategory)
                    s = s + "," + CategoryConversion.categories[category];
              if (showImageName)
                   s = s + "," + "'" + imageFileName + "'";
              if (showMessage)
                    s = s + "," + message;
              if (showStatus)
                   s = s + "," + status;
              if (showDueDateTime)
                    s = s + ", " + dueDateTime.get(Calendar.MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.YEAR);
                    s = s + "  " + dueDateTime.get(Calendar.HOUR);
                    s = s + ":" + dueDateTime.get(Calendar.MINUTE);
                    s = s + ":" + dueDateTime.get(Calendar.SECOND);
              if (showReminderInterval)
                    s = s + ", " + reminderInterval.get(Calendar.MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.YEAR);
                    s = s + "  " + reminderInterval.get(Calendar.HOUR);
                    s = s + ":" + reminderInterval.get(Calendar.MINUTE);
                    s = s + ":" + reminderInterval.get(Calendar.SECOND);
              if (showTerminatedDateTime)
                    s = s + ", " + terminatedDateTime.get(Calendar.MONTH);
                    s = s + "/" + terminatedDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" +terminatedDateTime.get(Calendar.YEAR);
                    s = s + "  " + terminatedDateTime.get(Calendar.HOUR);
                    s = s + ":" + terminatedDateTime.get(Calendar.MINUTE);
                    s = s + ":" + terminatedDateTime.get(Calendar.SECOND);
               return s;
          //******************COMPARE TO OBJECT*********************************
          public int compareTo(Object r)
               ReminderClass x;
               x = (ReminderClass)r;
               if (
                   (x.getCategory() == this.category)
               && (x.getDescription().equals(this.description))
               && (x.getMessage().equals(this.message))
               && (x.getImageFileName().equals(this.imageFileName))
               && (x.getDueDateTime().equals(this.dueDateTime))
               && (x.getReminderInterval().equals(this.reminderInterval))
               && (x.getTerminatedDateTime().equals(this.terminatedDateTime))
              return 0;
               else     
              return 1;
          //*************** ACCESSORS AND MUTATORS INCLUDING DISPLAY STYLE*******
          public void setDisplayStyle(int newDisplayStyle)
               displayStyle = newDisplayStyle;
          public int getDisplayStyle()
               return displayStyle;
          public int getCompareKey()
               return compareKey;
          public void setCompareKey(int newCompareKey)
               compareKey = newCompareKey;
          public int getCategory()
               return category;
          public void setImageFileName(String newFileName)
               imageFileName = newFileName;
          public String getImageFileName()
               return imageFileName;
          public void setCategory(int newCategory)
               category = newCategory;
          public String getDescription()
               return description;
          public void setDescription(String newDescription)
               description = newDescription;
          public void setImageArray(String[] array)
               imageArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imageArray[n] = array[n];
          public void setImagePathArray(String[] array)
               imagePathArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imagePathArray[n] = array[n];
          public String getImagePathArray(int index)
               return imagePathArray[index];
          public void populateComboBox(JComboBox jcb)
               for (int n = 0; n<numImages; n++)
                     jcb.addItem(imageArray[n]);
          public void addImageToArray(String s)
               imageArray[numImages] = s;
               numImages++;
          public String getMessage()
               return message;
          public void setMessage(String newMessage)
               message = newMessage;     
          public GregorianCalendar getDueDateTime()
               return dueDateTime;
          public void setDueDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                    int newSecs)
              dueDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);           
          public GregorianCalendar getReminderInterval()
               return reminderInterval;
          public void setReminderInterval(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
               reminderInterval = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);
          public GregorianCalendar getTerminatedDateTime()
               return terminatedDateTime;
          public void setTerminatedDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
              terminatedDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);      
          public String getStatus()
               return status;
          public void setStatus(String selection)
               status = selection;
          static public void setShowDate(boolean state)
               showDate = state;
          static public boolean getShowDate()
               return showDate;
          static public void setShowCategory(boolean state)
               showCategory = state;
          static public boolean getShowCategory()
               return showCategory;
          static public void setShowImageName(boolean state)
               showImageName = state;
          stat                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

    You don't really expect us to read through 300 lines of code do you?
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    In the meantime I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html]How to Use Combo Boxes for a working example that does exactly what you want.

  • Problem with JComboBox in j2sdk 1.4.2_01

    Hi,
    I've got a JComboBox, and I want to change its background color. I use this code:
    BasicComboBoxEditor editor = (BasicComboBoxEditor)myJComboBox.getEditor();
    editor.getEditorComponent().setBackground(SystemColor.control);
    This code works with versions 1.3.1 and 1.4.1, but with version 1.4.2_01 it doesn't.
    Can anyone tell me another way to change the background color??
    Thanx in advance.

    Hi,
    I've got a JComboBox, and I want to change its background color. I use this code:
    BasicComboBoxEditor editor = (BasicComboBoxEditor)myJComboBox.getEditor();
    editor.getEditorComponent().setBackground(SystemColor.control);
    This code works with versions 1.3.1 and 1.4.1, but with version 1.4.2_01 it doesn't.
    Can anyone tell me another way to change the background color??
    Thanx in advance.

  • Jtree Node with JComboBox don't work properly in Windows Vista!

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • Search a file with JComboBox

    Can anyone help me, i'm doing a sistem where there will be a JComboBox and when i choose the value which is a folder name in the combo it have to search the in the folder look for a file for example oratab. if the file in not found in the folder a message have to display file not found. once the file is found the content in the file have to display in a JListBox. CAN ANYONE HELP ME... I'M RUNNING OUT OF TIME...

    What's wrong with using a JFileChooser, which is actually designed for selecting files?

  • JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4

    Hello - this is one for the experts!
    I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
    However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
    1. Editing Cells and then advancing to the next column using tab.
    Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
    2. Editable JComboBox editors and and advancing to the next column using tab.
    Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
    With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
    (i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
    package com.test;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableTest4 extends JFrame {
         private JTable table;
         private DefaultTableModel tableModel;
         public TableTest4() {
              initFrame();
          * Initialises the test frame.
         public void initFrame() {
              // initialise table
              table = new JTable(10, 5);
              tableModel = (DefaultTableModel) table.getModel();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setRowHeight(22);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
              JButton dummyBtn1 = new JButton("Dummy Button 1");
              JButton dummyBtn2 = new JButton("Dummy Button 2");
              // initialise frame
              JPanel btnPanel = new JPanel(new GridLayout(2, 1));
              btnPanel.add(dummyBtn1);
              btnPanel.add(dummyBtn2);
              getContentPane().add(btnPanel, BorderLayout.SOUTH);
              // set renderer of first table column to be an editable combobox
              JComboBox editableCombo = new JComboBox();
              editableCombo.setEditable(true);
              TableColumn firstColumn = table.getColumnModel().getColumn(0);
              firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
         public static void main(String[] args) {
              TableTest4 frame = new TableTest4();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);

    Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
    I don't believe by adding a key listener to the cell editors will have the desired effect.
    I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
    Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating !

  • Help with JComboBox and Model creation

    hi,
    I'm trying to figure out the best way to set up the data behind the JComboBox and copy part of that data to be shown by the JComboBox. Here is what I would like it to do.
    My data:
    itemID, dbaseID, name
    1, 2, test1
    2, 2, test2
    3, 2, test3
    The JCombo will only display the name in this case "test1", "test2", or "test3". However when the user selects the name, I want to easily retrieve the hidden itemID or dbaseID. I've got the combobox working with just the "test1" but it doesn't tell me which dbase it is from. I have to search all of them and worry about identical names.
    What is the best way to set this up? I was thinking about an multiDimensional model but not sure how that would look. It is just not clicking how set up the data and then add parts of to the combo box.
    Any guidance or examples would be appreciated.

    From what I can tell both getSelectedItem() and getSelectedValue() return the string value of the GUI component. Read the API, that is not what they return. They return the "selected" Object.
    The renderer, by default, displays the toString() value of the Object.
    I'm casting the string into Item No you aren't, because that is not possible.
    My understanding was casting was just converting one thing to another.Casting does not "convert" anything. Time to get out your Java textbook and read up on casting.
    However this looks like it is actually grabbing the memory point to an item.Exactly. The getSelected... methods simply return a reference to the Object that was selected. Thats all any get... method does.

  • Help with JcomboBoxes

    Hi,
    Im having trouble with a combobox
    I have created a bean class for an ftp site, that contains;
    - ftp site name
    - address
    - username
    - password
    I then create an array of these sites and add them to the jComboBox.
    I only want to display the ftp site name in the box, however, when i select a certain site, i then want to pass the rest of the info. (ie. address, username, and password) to a connect method i have in another class.
    I'm quite sure this is a reasonably simply task but i just cant get my head around it.
    can anybody please help me?
    Much Thanks!

    Check out this posting for a solution:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613731

Maybe you are looking for