Resetting ComboBox

Hello everyone,
I would appreciate if someone could help me solve this problem. It's something simple but it seems that I'm doing something wrong and I don't know what. I have a user defined field in a form and I want to add some values to it (it's a combo box) with code. I managed to add the values, but I cannot erase them so the comboBox will reset with new values.
The addon works this way: The user enters a client code, when it validates (itemevent) the addon searchs all it's addresses and add them to the comboBox for the user to select one. The problems shows when I change the client code and validates it again, it should erase all addresses that were entered before and add the new ones (the ones that that client has), but it doesn't erase them. I tried some code that was posted in this forum with no success. My code is:
oItem = oForm.Items.Item("U_DCLIENTE")
        oForm.Items.Item("U_DCLIENTE").DisplayDesc = True
        direccCliente = oItem.Specific
        Dim a As Integer
        i = 1
Try
If direccCliente.ValidValues.Count > 0 Then
direccCliente.ValidValues.Add("", "")
direccCliente.Select(direccCliente.ValidValues.Count - 1, SAPbouiCOM.BoSearchKey.psk_Index)
For j = 1 To direccCliente.ValidValues.Count
direccCliente.ValidValues.Remove(direccCliente.ValidValues.Item("j").Value, SAPbouiCOM.BoSearchKey.psk_Index)
Next j
End If
Catch ex As Exception
'leave blank
End Try 
        Try
            sbors.DoQuery("select address from ALARSA_D.CRD1 t0 inner join ALARSA_D.OCST t1 on state=Code where CardCode = '" & codMinusc & "' or CardCode='" & codMayusc & "'")
            sbors.MoveFirst()
        Catch ex As Exception
            aplicacion.MessageBox("Ese cliente no tiene ninguna dirección")
        End Try
        a = sbors.RecordCount
        While i <= a
            direccCliente.ValidValues.Add("" & i & "", sbors.Fields.Item(0).Value)
            sbors.MoveNext()
            i = i + 1
        End While
    End Sub
Ca anybody help me? Thank you very much!

Hello Adele, thank you for your quick reply. I changed my code and put what you told me and also wrote what another topic of the forum says about resetting comboBox. The thing is that something very strange happened: I was debugging my project to see if it shows an error or works, and when the program gets to this line:
direccCliente.Select(direccCliente.ValidValues.Count - 1, SAPbouiCOM.BoSearchKey.psk_Index)
it returns to the ItemEvent function!!! I don't know how this does it! it's like I had a "return" or somethig there. So, it keeps executing but keeps returning to the preview function everytime it gets to that line.
Do you know what can it be?
I've noticed something, when it tries to execute the line I wrot before, it returns to the break point that's before that line! But if I put the break point after that line, it just freeze and stops.
Another thing, I erased two lines and just use this code:
Try
            If direccCliente.ValidValues.Count > 0 Then
                For j = direccCliente.ValidValues.Count - 1 To 0 Step -1
                    direccCliente.ValidValues.Remove(0, SAPbouiCOM.BoSearchKey.psk_Index)
                Next j
            End If
        Catch ex As Exception
            'leave blank
        End Try
An exception is thrown: {"Item - The item is not a user-defined item"}     System.Exception
What does it mean? The comboBox I'm using is an user defined field created in SBO (not by code). Why does it tells me that that item is not an user define field?
THANKS!!!!!
Message was edited by: BOne Altim
Message was edited by: BOne Altim

Similar Messages

  • How can I make it another way

    Can you please answer why my code so much difficult, is there way as this easier to write
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class TestComboBox extends JFrame {
        private JPanel mainPanel;
        private JComboBox[] combo;
        private JComboBox cb;
        private JComboBox presentCombo;
        private JComboBox previousCombo;
        private JButton button;
        private String selComboName;
        private String selItem;
        private String[] comboNames = {"one", "two", "three", "four", "five", "six", "seven"};
        private ArrayList<String> lockedList = new ArrayList<String>();
        private ArrayList<String> lastList = new ArrayList<String>();
        private static final int BUTTON_DISTANCE_Y = 15;
        private static final int BUTTON_WIDTH = 200, BUTTON_HEIGHT = 30;
        private Boolean isReseted = false;
        public TestComboBox() {
            addPanel();
            addCombos();
            addButton();
            add(mainPanel, BorderLayout.CENTER);
            presentCombo = null;
            previousCombo = null;
            setFirstFocus();
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    UIManager.put("ComboBox.disabledForeground", Color.darkGray);
                    TestComboBox mainFrame = new TestComboBox();
                    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    mainFrame.setSize(new Dimension(600, 370));
                    mainFrame.setLocationRelativeTo(null);
                    mainFrame.setVisible(true);
        private void addPanel() {
            mainPanel = new JPanel(null);
            mainPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
            mainPanel.setBackground(Color.GREEN);
        private void addButton() {
            button = new JButton("Reset ComboBox");
            button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonActionPerformed(evt);
                private void buttonActionPerformed(ActionEvent evt) {
                    resetCombos();
            button.setBounds(380, 20, 200, 30);
            mainPanel.add(button);
        private void addCombos() {
            combo = new JComboBox[comboNames.length];
            int i = 0;
            int in = 0;
            for (i = 0; i < comboNames.length; ++i) {
                combo[i] = new JComboBox();
                combo.setName(new String(comboNames[i]));
    combo[i].setBounds(20, ((BUTTON_DISTANCE_Y + BUTTON_HEIGHT) * i) + 20,
    BUTTON_WIDTH, BUTTON_HEIGHT);
    combo[i].addItem(new String("-"));
    for (in = 0; in < comboNames.length; ++in) {
    combo[i].addItem(new String(comboNames[in]));
    combo[i].setMaximumRowCount(5);
    combo[i].addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    if (isReseted != true) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
    Object eventSource = e.getSource();
    if (eventSource instanceof JComboBox) {
    cb = (JComboBox) e.getSource();
    if (cb == combo[0]) {
    lastCombo(combo[0]);
    } else if (cb == combo[1]) {
    lastCombo(combo[1]);
    } else if (cb == combo[2]) {
    lastCombo(combo[2]);
    } else if (cb == combo[3]) {
    lastCombo(combo[3]);
    } else if (cb == combo[4]) {
    lastCombo(combo[4]);
    } else if (cb == combo[5]) {
    lastCombo(combo[5]);
    } else if (cb == combo[6]) {
    lastCombo(combo[6]);
    mainPanel.add(combo[i]);
    private void resetCombos() {
    presentCombo = null;
    previousCombo = null;
    selComboName = "";
    selItem = "";
    lockedList.clear();
    lastList.clear();
    isReseted = true;
    unLockAllCombos();
    isReseted = false;
    setFirstFocus();
    private void unLockAllCombos() {
    int in = 0;
    for (in = 0; in < combo.length; ++in) {
    combo[in].setSelectedIndex(0);
    combo[in].setEnabled(true);
    private void lockCombo() {
    int in = 0;
    for (in = 0; in < combo.length; ++in) {
    if (((combo[in].getName()).equals(previousCombo.getName()))) {
    if (!((combo[in].getSelectedItem().toString()).equals("-"))) {
    combo[in].setEnabled(false);
    break;
    private void unlockCombo() {
    int lastComboInt = lockedList.size();
    String lastComboName = (lockedList.get(lastComboInt - 1)).toString();
    lastComboName = lastComboName.substring(1, (lastComboName.length()) - 1);
    int in = 0;
    for (in = 0; in < combo.length; ++in) {
    if (((combo[in].getName()).equals(lastComboName))) {
    combo[in].setEnabled(true);
    if (lastComboInt < 1) {
    lockedList.clear();
    } else if (lastComboInt > 1) {
    lockedList.remove(lastComboInt - 1);
    break;
    to be continued ....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

        private void lastCombo(JComboBox lcb) {
            if ((presentCombo == null) && (previousCombo == null)) {
                presentCombo = new JComboBox();
                presentCombo = lcb;
                presentCombo.setName(lcb.getName());
                selComboName = presentCombo.getName();
                selItem = presentCombo.getSelectedItem().toString().trim();
                lastList.add(selComboName);
            } else if ((presentCombo != null) && (previousCombo == null)) {
                lockedList.add(lastList.toString());
                lastList.clear();
                previousCombo = new JComboBox();
                previousCombo = presentCombo;
                previousCombo.setName(presentCombo.getName());
                lockCombo();
                presentCombo = lcb;
                presentCombo.setName(lcb.getName());
                selComboName = presentCombo.getName();
                selItem = presentCombo.getSelectedItem().toString().trim();
                lastList.add(new String(selComboName));
            } else if ((presentCombo != null) && (previousCombo != null)) {
                if (lcb.getSelectedItem().toString().equals("-")) {
                    unlockCombo();
                } else {
                    lockedList.add(lastList.toString());
                    lastList.clear();
                    previousCombo = new JComboBox();
                    previousCombo = presentCombo;
                    previousCombo.setName(presentCombo.getName());
                    lockCombo();
                    presentCombo = lcb;
                    presentCombo.setName(lcb.getName());
                    selComboName = presentCombo.getName();
                    selItem = presentCombo.getSelectedItem().toString().trim();
                    lastList.add(new String(selComboName));
        private void setFirstFocus() {
            Runnable doRun = new Runnable() {
                public void run() {
                    combo[0].setSelectedIndex(0);
                    combo[0].getEditor().selectAll();
                    combo[0].requestFocus();
            SwingUtilities.invokeLater(doRun);
    }... kopik

  • "Reset" a DropdownBox / ComboBox

    Hi everybody,
    I'm trying to realize some kind of a form reset functionality.
    To achieve this, I save the current values of the form fields with
    formField.data("oldVal",formField.getValue());
    and if the form needs to be resetted, i simply call
    formField.setValue(formField.data("oldVal"));
    This works like charme, if I'm using it for TextField controls. But as soon as it comes to a DropdownBox control, a strange behavior occurs.
    I tried several different approaches:
    // approach 1
    dropdownBox.data("oldVal",dropdownbox.getSelectedKey());
    dropdownBox.setSelectedKey(data("oldVal"));
    // approach 2
    dropdownBox.data("oldVal",dropdownbox.getSelectedItemId());
    dropdownBox.setSelectedItemId(data("oldVal"));
    // approach 3
    dropdownBox.data("oldVal",dropdownbox.getListBox());
    dropdownBox.setListBox(data("oldVal"));
    I even tried to combine these approaches. But all resulted in the same strange behavior:
    If I select a different ListItem in the DropdownBox and use my reset-function afterwards, the selected ListItem is switched back to the one that was selected before, BUT the other ListItem (that was selected, before I tried to reset the form) now has the same text and key as the ListItem that is selected after the reset. Calling dropdownBox.clearHistory() afterwards, doesn't help, either.
    Example: Change from ListItem 1 ("Hello") to ListItem 2 ("Goodbye"). After reset: ListItem 1 is selected again (good!). The text of ListItem 2 has changed to "Hello". So if I click on the Dropdown now, I have 2x "Hello" now and "Goodbye" is gone.
    What am I doing wrong here? Thanks for your help in advance!
    Regards,
    René

    This had to do with a TwoWay JsonModel. When changing the Dropdown value, I changed the binding of other form fields as well, but didn't change the binding back when resetting the form. When resetting, I then wrote the old values back to the other form fields and the TwoWay BindingMode wrote those values back to the Model, which was still pointing to the new path set when changing the Dropdown value.
    Hope this makes sense. Anyway, the final solution has to be changing the BindingMode to OneWay.

  • Trying to write a Listener on a CheckBox to change the Model of a ComboBox

    I am trying to change the list that appears in a ComboBox dynamically based on if a CheckBox is selected or not. I have multiple CheckBoxes and ComboBoxes being created in a loop based on a variable assigned at creation. Every tutorial i have seen writes out a listener that explicitly defines the checkbox instance but in my case i don't acctually know. My checkboxes are in an array of checkboxes as are the comboboxes as they are being created at runtime. Any help would be much apreciated this issue has been with me for two days now.

    here is a snippit of my code in how i was implementing this:
    int numButton = 17; //this is for testing only, this variable is set from another class normally
    // these variables are defined private elsewhere in the class
    JCheckBox PlayerByeCheck[] = new JCheckBox[numButton + 1];
    JCheckBox PlayerHomeCheck[] = new JCheckBox[numButton + 1];
    boolean PlayerOnBye[] = new boolean[numButton + 1];
    for (int i = 1; i <= numButton; i++) {
             PlayerByeCheck[i] = new JCheckBox();
         PlayerHomeCheck[i] = new JCheckBox();
         PlayerOnBye[i] = false;
    // more code here for building the gui it is not important for this problem
    // code to build the list starts here
    for (int i = 1; i <= numButton; i++) {
         ((TableLayout)PlayerRosterPanel.getLayout()).insertRow(1, TableLayout.PREFERRED);
             PlayerByeCheck.setOpaque(false);
         PlayerByeCheck[i].addItemListener(this);
         PlayerByeCheck[i].setName("PlayerByeCheck" + i);
         PlayerRosterPanel.add(PlayerByeCheck[i], new TableLayoutConstraints(2, 1, 2, 1, TableLayoutConstraints.CENTER, TableLayoutConstraints.FULL));
    //the comboox that i want to change
    //---- PlayerTeamSelect1 ----
         if (PlayerOnBye[i] = true) {
              PlayerTeamSelect[i].setModel(new DefaultComboBoxModel(new String[] {
                   "ARI",
                   "ATL",
                   "BAL",
              "BUF",
         "BYE"
              PlayerTeamSelect[i].setSelectedItem("BYE");
         } else {
              PlayerTeamSelect[i].setModel(new DefaultComboBoxModel(new String[] {
                   "ARI",
                   "ATL",
                   "BAL",
                   "BUF",
                   "CAR",
              "BYE"
         PlayerTeamSelect[i].setOpaque(false);
         PlayerRosterPanel.add(PlayerTeamSelect[i], new TableLayoutConstraints(4, 1, 4, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
    //more gui code here method gets closed
    //Item Action Listener starts here this is where i am having the problem                         
    public void itemStateChanged(ItemEvent e) {
         Object source = e.getItem();
         if (source == PlayerByeCheck[1])
         int select = e.getStateChange();
              if (select == ItemEvent.SELECTED)
              PlayerOnBye[1] = true;
    PlayerRosterPanel.repaint();
    //repaint the window i think can't get the listener to work to see if this is the right way to do this
    //i doubt it is
    I have tried several different ways to write the listener, the example in the code above is following the java swing tutorial by explicitly defining the checkbox. I have tried to write the listener as i am creating the checkbox, which doesn't seem to work or i am wrting it wrong, which is entirely possible. Once the listener sets the value i think it should repaint the screen but i am sure that that is wrong right now as well. As my hunch is the repaint will reset the checkbox to DESELCTED the default value. I will come to that issue once i figure out how to get the listener working. Ideally i want to be able to set the listener for the checkboxes regardless as to how many there are. As stated above i am generating a list of checkboxes, comboboxes and other fields based on a variable that is defined in one of my objects. If the user selects checkbox 3 than combobox 3 should be changed, and the others should not. if the user selects all the checkboxes than all the comboboxes change.
    thanks for any help. Still plugging along on it trying to figure this one out.

  • ComboBox not displaying values...

    Hi people,
    I am having a problem, when I run my GUI the ComboBoxes refuse to display the data when I click the search buttons, my code is below (there are 5 separate classes)
    Here is my code:
    MusicListTest.java:
    import java.util.*;
    class MusicListTest
         /* Test */
         public static void main (String[] arg)
              MusicList tMusic = new MusicList();
              tMusic.addMusic(new Music("Reanimation", "Linkin Park", "Ripcord Designs", "5", "July", "2004"));
              tMusic.addMusic(new Music("Black", "Metallica", "Virgin Records", "8","August","2004"));
              //tMusic.addMusic(new Music("1", "2", "3", "Thusday 2nd July 2004"));
              /*tMusic.addMusic(new Music("Maybe", "Linkin Park", "Ripcord Designs"));
              tMusic.addMusic(new Music("Garage", "Metallica", "Virgin Records"));
              tMusic.addMusic(new Music("1", "2", "3"));
              tMusic.addMusic(new Music("The Wall", "Pink Floyd", "MorningStar Records"));*/
              System.out.println(tMusic);
              //System.out.println(tMusic1);
              //System.out.println(tMusic);
              //Initiate the GUI with the current list of names.
              MusicListGUI tGui = new MusicListGUI(tMusic);
    MusicInputComponent.java:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    class MusicInputComponent extends JComponent
         //Note: Make input components attributes, as other
         //      methods need to refer to them.
            private JTextField  iTitleField;
         private JTextField iAuthorField;
         private JTextField iPublisherField;
         private JComboBox iDayCombo;
         private JComboBox iMonthCombo;
         private JComboBox iYearCombo;
         public MusicInputComponent()
                    //Dimensions for prompts so that all are the same size and line up.
              Dimension d = new Dimension(583,300);
              Dimension e = new Dimension(60,20);
                    Dimension f = new Dimension(100,20);
                    JPanel tPanel;
              JPanel tPanel1;
              //----Title-------------------------------------
              //Create prompt label, and combo box objects
              JTabbedPane tTabPane = new JTabbedPane(JTabbedPane.TOP);
              tTabPane.setPreferredSize(d);
                    tPanel = new JPanel();
                    tPanel1 = new JPanel();
                    iTitleField = new JTextField(40);
                    iAuthorField = new JTextField(40);
                    iPublisherField = new JTextField(40);
                    String[] tDays = {"","1","2","3","4","Mr","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
                    String[] tMonths = {"","January","February","March","April","May","June","July","August","September","October","November","December"};
                    String[] tYears= {"","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010"};
                    iDayCombo = new JComboBox(tDays);
                    iMonthCombo = new JComboBox(tMonths);
                    iYearCombo = new JComboBox(tYears);
                    JLabel tTitlePrompt = new JLabel("Title:", JLabel.RIGHT);
                    JLabel tAuthorPrompt = new JLabel("Author:", JLabel.RIGHT);
                    JLabel tPublisherPrompt = new JLabel("Publisher:", JLabel.RIGHT);
                    tTitlePrompt.setPreferredSize(e);
                    tAuthorPrompt.setPreferredSize(e);
                    tPublisherPrompt.setPreferredSize(e);
                    iDayCombo.setPreferredSize(e);
                    iMonthCombo.setPreferredSize(f);
                    iYearCombo.setPreferredSize(e);
              Box tMainBox = Box.createHorizontalBox();
              tMainBox.add(Box.createHorizontalStrut(10));
              tMainBox.add(tTitlePrompt);
              tMainBox.add(Box.createHorizontalStrut(10));
              tMainBox.add(iTitleField);
              tMainBox.add(Box.createHorizontalStrut(10));
              tMainBox.add(tAuthorPrompt);
              tMainBox.add(Box.createHorizontalStrut(10));
              tMainBox.add(iAuthorField);
              tMainBox.add(Box.createHorizontalStrut(10));
                    tMainBox.add(tPublisherPrompt);
              tMainBox.add(Box.createHorizontalStrut(10));
              tMainBox.add(iPublisherField);
                    tMainBox.add(Box.createHorizontalStrut(10));
                    tMainBox.add(iDayCombo);
                    tMainBox.add(Box.createHorizontalStrut(10));
                    tMainBox.add(iMonthCombo);
                    tMainBox.add(Box.createHorizontalStrut(10));
                    tMainBox.add(iYearCombo);
                    tMainBox.add(Box.createHorizontalStrut(10));
                    tPanel.add(tTitlePrompt);
                    tPanel.add(iTitleField);
                    tPanel.add(tAuthorPrompt);
                    tPanel.add(iAuthorField);
                    tPanel.add(tPublisherPrompt);
                    tPanel.add(iPublisherField);
                    tPanel.add(iDayCombo);
                    tPanel.add(iMonthCombo);
                    tPanel.add(iYearCombo);
                    tPanel.setBackground(new Color(200, 221, 242));
                    tPanel1.setBackground(new Color(200, 221, 242));
                    /*Object iM2 = iM.AList();
                    DefaultListModel iD = new DefaultListModel();
                    iD.addElement(iM2);
                    tList = new JList(iD);*/
                    //tList.setBackground(new Color(200, 221, 242));
                    //Box tNameBox = Box.createVerticalBox();
                    JLabel tLabel = new JLabel("Welcome to my CD selector utility, written by: Robert William Rainbird - P03301169", JLabel.CENTER);
                    tTabPane.addTab("Information", tLabel);
              tTabPane.addTab("Details", tPanel);
                    //tTabPane.addTab("D", tList);
              this.setLayout(new FlowLayout(FlowLayout.LEFT));
              this.add(tTabPane);
         //----accessors-------------------------
         //Return a Name object built form the input fields
         public Music getMusicInput()
              return new Music(getTitle(), getAuthor(), getPublisher(), getDay(), getMonth(), getYear());
         public String getTitle()
                    return iTitleField.getText().trim();
         public String getAuthor()
              return iAuthorField.getText().trim();
         public String getPublisher()
              return iPublisherField.getText().trim();
            public String getDay()
              return (String)iDayCombo.getSelectedItem();
         public String getMonth()
              return (String)iMonthCombo.getSelectedItem();
         public String getYear()
              return (String)iYearCombo.getSelectedItem();
         //-----modifiers: to allow setting contents for each field-------
         //Set the fields to display pName
         public void setMusicInput(Music pMusic)
              this.setTitle(pMusic.getTitle());
              this.setAuthor(pMusic.getAuthor());
              this.setPublisher(pMusic.getPublisher());
              iDayCombo.requestFocus();
              iMonthCombo.requestFocus();
              iYearCombo.requestFocus();
         //effectively clears the fields on previous inputs
         public void reset()
              setMusicInput(new Music("", "", "", "", "", ""));
         //pTitle must be one of "","Mr", "Mrs", "Miss", "Ms", "Dr", "Prof"
         public void setTitle(String pTitle)
              iTitleField.setText(pTitle);
         public void setAuthor(String pAuthor)
              iAuthorField.setText(pAuthor);
         public void setPublisher(String pPublisher)
              iPublisherField.setText(pPublisher);
         public void setDay(String pDay)
              iDayCombo.setSelectedItem(pDay);
         public void setMonth(String pMonth)
              iMonthCombo.setSelectedItem(pMonth);
         public void setYear(String pYear)
              iYearCombo.setSelectedItem(pYear);
    Music.java
    public class Music
         private String iTitle;
         private String iAuthor;
         private String iPublisher;
            private String iDay;
            private String iMonth;
            private String iYear;
         public Music()
                    this("","","","","","");
         public Music(String pTitle, String pAuthor, String pPublisher, String pDay, String pMonth, String pYear)
              this.iTitle = pTitle;
              this.iAuthor = pAuthor;
              this.iPublisher = pPublisher;
              this.iDay = pDay;
              this.iMonth = pMonth;
              this.iYear = pYear;
         public String getTitle()
              return iTitle;
         public String getAuthor()
              return iAuthor;
         public String getPublisher()
              return iPublisher;
            public String getDay()
              return iDay;
            public String getMonth()
              return iMonth;
         public String getYear()
              return iYear;
         private String getFullDetails()
              return iTitle + " " + iAuthor + " " + iPublisher + " " + iDay + " " + iMonth + " " + iYear;
         public String getMusicLine()
              return iTitle + ' ' + iAuthor.toUpperCase().charAt(0) + ' ' + iPublisher + ' ' + iDay + ' ' + iMonth + ' ' + iYear;
            public boolean equals(Object obj)
              if (obj==null || getClass()!=obj.getClass())
                   return false;
                   Music n = (Music) obj;
                   return iTitle.equalsIgnoreCase(n.iTitle)
                        && iPublisher.equalsIgnoreCase(n.iPublisher);
         public int hashCode()
              return getFullDetails().hashCode();
         public String toString()
              return getFullDetails();
    MusicList.java:
    import java.util.*;
    public class MusicList
                private List iList;  //names are stored in a list.
         public MusicList()
              iList = new LinkedList();
         public MusicList(List pListOfMusic)
              iList = pListOfMusic;
         public void addMusic(Music pMusicName)
                iList.add(pMusicName);
         public void removeMusic(Music pMusicName)
              iList.remove(pMusicName);
                 //Return the name with the given surname, otherwise return null.
         //Uses a linear search.
            public Music findTitle(String pTitle)
              Music tTitle = null;
              boolean found = false;
              Iterator it = iList.iterator();
              while (it.hasNext() && !found)
                   tTitle = (Music) it.next();
                   found = tTitle.getTitle().equalsIgnoreCase(pTitle);
              if(!found) tTitle=null;
              return tTitle;
         public Music findAuthor(String pAuthor)
              Music tAuthor = null;
              boolean found = false;
              Iterator it = iList.iterator();
              while (it.hasNext() && !found)
                   tAuthor = (Music) it.next();
                   found = tAuthor.getAuthor().equalsIgnoreCase(pAuthor);
              if(!found) tAuthor=null;
              return tAuthor;
            public Music findPublisher(String pPublisher)
              Music tPub = null;
              boolean found = false;
              Iterator it = iList.iterator();
              while (it.hasNext() && !found)
                   tPub = (Music) it.next();
                   found = tPub.getPublisher().equalsIgnoreCase(pPublisher);
              if(!found) tPub=null;
              return tPub;
         public String toString()
              return "Music List = " + iList.toString();
    MusicListGUI.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    class MusicListGUI extends JFrame
         private MusicList iMusicList;
         public MusicListGUI()
              this(new MusicList());
         public MusicListGUI(MusicList pMusicList)
                    super("CD List GUI");     //set the title
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    Container tContentPane = this.getContentPane(); //we add components to the contentPane
                    tContentPane.setLayout(new BorderLayout());
                    iMusicList = pMusicList;
                    MusicInputComponent tMusicInputCpt = new MusicInputComponent();
              JLabel tMessageLine = new JLabel();
                    ButtonPanel tBPanel = new ButtonPanel(tMusicInputCpt, tMessageLine, iMusicList);
              /* Use a tabbed pane. Each component has its own tab.*/
                    //add the tab pane to the frame's content.
                    tContentPane.add(tMusicInputCpt, BorderLayout.NORTH);
                    tContentPane.add(tBPanel, BorderLayout.WEST);
                    tContentPane.add(tMessageLine, BorderLayout.SOUTH);
                    tMessageLine.setText("Welcome");
                    this.setLocation(300,200);
              this.setResizable(false);
              this.pack();
              this.setVisible(true);                 //Then add the panel to the tab pane (or content pane).
         public MusicList getMusicList()
              return iMusicList;
         public void setMusicList(MusicList pMusicList)
              iMusicList = pMusicList;
    ButtonPanel.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    class ButtonPanel extends JPanel {
         private MusicInputComponent iMusicCpt;
         private JLabel iMessageLine;
         private MusicList iMusicList;
         public ButtonPanel(MusicInputComponent pMusicCpt, JLabel pMessageLine, MusicList pMusicList)
              iMusicCpt = pMusicCpt;
              iMessageLine = pMessageLine;
              iMusicList = pMusicList;
              //Define the buttons and listener methods ----------------------------
              JButton tFindButton = new JButton("Search Title");
              tFindButton.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                                            Music tMusic = iMusicCpt.getMusicInput();
                             iMessageLine.setText("Searching for: ");
                                            String tTitle = tMusic.getTitle();
                                            tMusic = iMusicList.findTitle(tTitle);
                                            if (tMusic != null)
                                  iMusicCpt.setMusicInput(tMusic);
                                  iMessageLine.setText(iMessageLine.getText() + " - found");
                             else
                                  iMessageLine.setText(iMessageLine.getText() + " - not found");
              JButton tFindButton1 = new JButton("Search Author");
              tFindButton1.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             Music tMusic = iMusicCpt.getMusicInput();
                             iMessageLine.setText("Searching for: ");
                                            String tAuthor = tMusic.getAuthor();
                                            tMusic = iMusicList.findAuthor(tAuthor);
                                            if (tMusic != null)
                                  iMusicCpt.setMusicInput(tMusic);
                                  iMessageLine.setText(iMessageLine.getText() + " - found");
                             else
                                  iMessageLine.setText(iMessageLine.getText() + " - not found");
              JButton tFindButton2 = new JButton("Search Publisher");
              tFindButton2.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             Music tMusic = iMusicCpt.getMusicInput();
                             iMessageLine.setText("Searching for: ");
                                            String tPublisher = tMusic.getPublisher();
                                            tMusic = iMusicList.findPublisher(tPublisher);
                                            if (tMusic != null)
                                  iMusicCpt.setMusicInput(tMusic);
                                  iMessageLine.setText(iMessageLine.getText() + " - found");
                             else
                                  iMessageLine.setText(iMessageLine.getText() + " - not found");
              JButton tClearButton = new JButton("Clear");
              tClearButton.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             iMusicCpt.reset();
                             iMessageLine.setText("Enter\n" + "Details");
              JButton tSubmitButton = new JButton("Submit");
              tSubmitButton.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             Music tMusic = iMusicCpt.getMusicInput();
                                            iMusicList.addMusic(tMusic);
                             iMessageLine.setText("Added: " + tMusic.toString());
                             System.out.println(iMusicList);
              JButton tDeleteButton = new JButton("Delete");
              tDeleteButton.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             Music tMusic = iMusicCpt.getMusicInput();
                             iMusicList.removeMusic(tMusic);
                             iMessageLine.setText("Deleted: " + tMusic.toString());
                             iMusicCpt.reset();
                             System.out.println(iMusicList);
              //Construct the ButtonPanel -----------------
              this.setLayout(new FlowLayout(FlowLayout.RIGHT));
              //this.setBackground(Color);
              this.add(tFindButton);
              this.add(tFindButton1);
              this.add(tFindButton2);
                    this.add(tDeleteButton);
              this.add(tClearButton);
              this.add(tSubmitButton);
    }Any light anyone could shed on the situation would be appreciated, I have another GUI with a ComboBox and it allows you to Clear the ComboBox and display search results, my own one and the reference one are both the same (I think)
    Many Thanks,
    Rob.

    Yeah...well you need everything for it to run correctly. And see if there are any mistakes. Not quite. We are not here to debug your programs for you. We are here to help with programming concepts and questions.
    Write a simple program with all the code in one class that demonstrates the problem. Chances are you will find out what you problem is. If you can prove it works in a simple program the you find out what the difference is between the working and non working program.
    Here is an examle of a simple class that responds to a combo box selection:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=428181

  • Resetting a form to default state

    I have a form with lots of swing components(JtextFields,JRadioButtons,JComboBoxes), and I want to be able to "reset" the form back to its' original state(i.e. blank textfields,no selected radiobutttons,comboboxes with defaults showing). Is there a single method to update the entire form to its' original state? Thanks.

    hello,
    done this before,
    what i did was, i create a function, in this function i have all the add functions i.e adding the objects to the container. everytime i want to reset the form, i call the removeAll() function which clears the frame from all components and then i call the function that adds the components to the frame example
    public someClass()
    addComponents();
    //actionPerformed method for a button that resets
    this.removeAll();
    addComponents();
    public void addComponents()
    //add all the stuff to the container
    }hope it makes some sense
    asrar

  • Who can help me :)--a problem with java program(reset problem in java )

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.The code like this,first one is shapes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }second one is drawpanel:
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    }If any kind people who can help me.
    many thanks to you!

    4 widgets???
    maybe this is what you mean.
    add this inside your actionPerformed method for the reset action
    squareButton.setSelected(true);
    colorComboBox.setSelectedIndex(0);
    if not be more clear in your post.

  • A problem with java program(reset problem in java GUY)

    I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
    correspond to the black square.
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel {
         public final static int CIRCLE = 1, SQUARE = 2;
         private int shape;
         private boolean fill;
         private boolean showStatus;
        private int shapeSize = 100;
        private Color foreground;
         // draw a specified shape
        public void paintComponent (Graphics g){
              super.paintComponent(g);
              // find center
            int x=(getSize().width-shapeSize)/2;
              int y=(getSize().height-shapeSize)/2;
              if (shape == CIRCLE) {
                 if (fill == true){
                     g.setColor(foreground);
                      g.fillOval(x, y, shapeSize, shapeSize);
                else{
                       g.setColor(foreground);
                    g.drawOval(x, y, shapeSize, shapeSize);
              else if (shape == SQUARE){
                 if (fill == true){
                     g.setColor(foreground);
                        g.fillRect(x, y, shapeSize, shapeSize);
                else{
                        g.setColor(foreground);
                    g.drawRect(x, y, shapeSize, shapeSize);
        // set showStatus value
        public void setShowStatus (boolean s) {
              showStatus = s;
         // return showstatus value
        public boolean getShowStatus () {
              return showStatus;
         // set fill value
        public void setFill(boolean isFill) {
              fill = isFill;
         // set shape value
        public void setShape(int shapeToDraw) {
              shape = shapeToDraw;
        // set shapeSize value
        public void setShapeSize(int newShapeSize) {
              shapeSize = newShapeSize;
        // set foreground value
        public void setForeground(Color newColor) {
              foreground = newColor;
         // repaint DrawPanel
        public void draw (){
              if(showStatus == true)
              repaint();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class shapes extends JFrame {
         private JPanel buttonPanel; // panel for buttons
         private DrawPanel myPanel;  // panel for shapes
         private JButton resetButton;
        private JComboBox colorComboBox;
         private JRadioButton circleButton, squareButton;
         private ButtonGroup radioGroup;
         private JCheckBox filledButton;
        private JSlider sizeSlider;
         private boolean isShow;
         private int shape;
         private boolean isFill=true;
        private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
                                   "green", "lightgray", "magenta", "orange",
                                   "pink", "red", "white", "yellow"};   // color names list in ComboBox
        private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
                              Color.gray, Color.green, Color.lightGray, Color.magenta,
                              Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
         public shapes() {
             super("Draw Shapes");
             // creat custom drawing panel
            myPanel = new DrawPanel(); // instantiate a DrawPanel object
            myPanel.setBackground(Color.white);
             // set up resetButton
            // register an event handler for resetButton's ActionEvent
            resetButton = new JButton ("reset");
             resetButton.addActionListener(
              // anonymous inner class to handle resetButton events
                 new ActionListener() {
                       // draw a black filled square shape after clicking resetButton
                     public void actionPerformed (ActionEvent event) {
                             // call DrawPanel method setShowStatus and pass an parameter
                          // to decide if show the shape
                         myPanel.setShowStatus(true);
                             isShow = myPanel.getShowStatus();
                             shape = DrawPanel.SQUARE;
                         // call DrawPanel method setShape to indicate shape to draw
                             myPanel.setShape(shape);
                         // call DrawPanel method setFill to indicate to draw a filled shape
                             myPanel.setFill(true);
                         // call DrawPanel method draw
                             myPanel.draw();
                             myPanel.setFill(true);
                             myPanel.setForeground(Color.black);
                   }// end anonymous inner class
             );// end call to addActionListener
            // set up colorComboBox
            // register event handlers for colorComboBox's ItemEvent
            colorComboBox = new JComboBox(colorNames);
            colorComboBox.setMaximumRowCount(5);
            colorComboBox.addItemListener(
                 // anonymous inner class to handle colorComboBox events
                 new ItemListener() {
                     // select shape's color
                     public void itemStateChanged(ItemEvent event) {
                         if(event.getStateChange() == ItemEvent.SELECTED)
                             // call DrawPanel method setForeground
                             // and pass an element value of colors array
                             myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
                        myPanel.draw();
                }// end anonymous inner class
            ); // end call to addItemListener
            // set up a pair of RadioButtons
            // register an event handler for RadioButtons' ItemEvent
             squareButton = new JRadioButton ("Square", true);
             circleButton = new JRadioButton ("Circle", false);
             radioGroup = new ButtonGroup();
             radioGroup.add(squareButton);
             radioGroup.add(circleButton);
            squareButton.addItemListener(
                // anonymous inner class to handle squareButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                           if (isShow==true) {
                                 shape = DrawPanel.SQUARE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                   }// end anonymous inner class
             );// end call to addItemListener
             circleButton.addItemListener(
                   // anonymous inner class to handle circleButton events
                new ItemListener() {
                       public void itemStateChanged (ItemEvent event) {
                             if (isShow==true) {
                                 shape = DrawPanel.CIRCLE;
                                 myPanel.setShape(shape);
                                 myPanel.draw();
                             else
                                 System.out.println("Please click Reset button first");
                   }// end anonymous inner class
             );// end call to addItemListener
             // set up filledButton
            // register an event handler for filledButton's ItemEvent
            filledButton = new JCheckBox("Filled", true);
             filledButton.addItemListener(
              // anonymous inner class to handle filledButton events
            new ItemListener() {
                  public void itemStateChanged (ItemEvent event) {
                    if (isShow==true) {
                            if (event.getStateChange() == ItemEvent.SELECTED) {
                                  isFill=true;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                            else {
                                isFill=false;
                                  myPanel.setFill(isFill);
                                  myPanel.draw();
                    else
                        System.out.println("Please click Reset button first");
              }// end anonymous inner class
             );// end call to addItemListener
            // set up sizeSlider
            // register an event handler for sizeSlider's ChangeEvent
            sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
            sizeSlider.setMajorTickSpacing(10);
            sizeSlider.setPaintTicks(true);
            sizeSlider.addChangeListener(
                 // anonymous inner class to handle sizeSlider events
                 new ChangeListener() {
                      public void stateChanged(ChangeEvent event) {
                          myPanel.setShapeSize(sizeSlider.getValue());
                             myPanel.draw();
                 }// end anonymous inner class
             );// end call to addChangeListener
            // set up panel containing buttons
             buttonPanel = new JPanel();
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
             buttonPanel.add(resetButton);
             buttonPanel.add(filledButton);
            buttonPanel.add(colorComboBox);
            JPanel radioButtonPanel = new JPanel();
            radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
            radioButtonPanel.add(squareButton);
            radioButtonPanel.add(circleButton);
            buttonPanel.add(radioButtonPanel);
            // attach button panel & draw panel to content panel
            Container container = getContentPane();
            container.setLayout(new BorderLayout(10,10));
            container.add(myPanel, BorderLayout.CENTER);
             container.add(buttonPanel, BorderLayout.EAST);
            container.add(sizeSlider, BorderLayout.SOUTH);
            setSize(500, 400);
             setVisible(true);
         public static void main(String args[]) {
             shapes application = new shapes();
             application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Many thanks

    Who is this Java guy anyway?

  • ComboBox issue

    So I am sure Jonathan groans when he sees my name pop up, but I found another ComboBox issue and I am looking for help finding a workaround.
    (I opened a JIRA - http://javafx-jira.kenai.com/browse/RT-27654)
    Seems that calling clearSelecion() on a ComboBox disallows selecting the same item that was selected when the clearSelection() was called. In my sample code, if you
    1) select 'a' - 'a' displays
    2) click reset button - 'a' disappears
    3) select 'a' - 'a' does NOT appear and it should
    The issue is major when the combobox only has a singe item
    package javafxapplication2;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.ResourceBundle;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ComboBox;
    * @author user
    public class SampleController implements Initializable {
        @FXML
        private ComboBox<MyObject> cb;
            private ObservableList<MyObject> myList = FXCollections.observableList(new ArrayList<MyObject>());
        @FXML
        private void handleButtonAction(ActionEvent event) {
            cb.getSelectionModel().clearSelection();
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            MyObject a = new MyObject("a", "A");
            MyObject b = new MyObject("b", "B");
            MyObject c = new MyObject("c", "C");
            myList.add(a);
            myList.add(b);
            myList.add(c);
            cb.setItems(myList);
        class MyObject {
            String key;
            String Value;
            public MyObject(String key, String Value) {
                this.key = key;
                this.Value = Value;
            @Override
            public String toString() {
                return key;
    <?xml version="1.0" encoding="UTF-8"?>
    <?import java.lang.*?>
    <?import java.util.*?>
    <?import javafx.collections.*?>
    <?import javafx.scene.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication2.SampleController">
      <children>
        <ComboBox fx:id="cb" layoutX="82.0" layoutY="78.0" prefWidth="160.0">
          <items>
          </items>
        </ComboBox>
        <Button onAction="#handleButtonAction" layoutX="130.0" layoutY="137.0" mnemonicParsing="false" text="Reset" />
      </children>
    </AnchorPane>

    Hi. Here is a workaround.
    //Modified  initialize method.  Added a null object to the list:
      @Override
        public void initialize(URL url, ResourceBundle rb) {
            MyObject a = new MyObject("a", "A");
            MyObject b = new MyObject("b", "B");
            MyObject c = new MyObject("c", "C");
            myList.add(a);
            myList.add(b);
            myList.add(c);
            myList.add(null);   
            cb.setItems(myList);
          Modified handleButtonAction(ActionEvent event) method:
    private void handleButtonAction(ActionEvent event) {
             cb.getSelectionModel().selectLast();
             cb.getSelectionModel().clearSelection();
        }

  • ComboBoxs outputting to a string

    Hi in this code I've created four comboBoxs and the selections from the comboBoxs then build a string and outputs it in label6. It does this ok but when the user changes a value in one of the comboBoxs the string does not update. I'm just not sure how to do it? Can anyone help?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Menu extends JPanel implements ActionListener
    private JButton Reset;
    private JButton Run;
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;
    private JLabel label6;
    private JLabel label7;
    private JComboBox EnsembleSize = null;
    private JComboBox Randomize;
    private JComboBox baseModel = null;
    private JComboBox dataChoices;
    final static int START_INDEX = 0;
    private String Configs;
    private String[] baseModelRun;
    private String[] dataRun;
    private String[] EnsembleSizeRun;
    private String[] RandomizeRun;
    public Menu()
         constructComboBoxs();
    constructComponents();
    addComponents();
    positionComponents();
    //Set ActionListeners
    Run.setActionCommand("RunButton");
    Run.addActionListener(this);
    Reset.setActionCommand("ResetButton");
    Reset.addActionListener(this);
    EnsembleSize.setActionCommand("ensemble");
    EnsembleSize.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if (e.getActionCommand().equals("RunButton"))
                   label5.setText("<html><font color=red>RUNNING NOW!!!</font></html>");
         //label6.setText(baseModelRun[baseModel.getSelectedIndex()]);
         label6.setText("Configs: " + Configs);
                        EnsembleSize.setEnabled(false);
                        baseModel.setEnabled(false);
                        Randomize.setEnabled(false);
                        dataChoices.setEnabled(false);
              else if(e.getActionCommand().equals("ResetButton"))
                   Toolkit.getDefaultToolkit().beep();
         label5.setText("");
         label6.setText("Configs: ");
                        EnsembleSize.setEnabled(true);
                        baseModel.setEnabled(true);
                        Randomize.setEnabled(true);
                        dataChoices.setEnabled(true);
              EnsembleSize.setSelectedIndex(0);
              baseModel.setSelectedIndex(0);
              Randomize.setSelectedIndex(0);
              dataChoices.setSelectedIndex(0);
         /*else if(e.getActionCommand().equals("ensemble"))
              //label6.setText(EnsembleSizeRun[EnsembleSize.getSelectedIndex()]);
         String petName = (String)EnsembleSize.getSelectedItem();
         label6.setText(petName);
              void constructComboBoxs()
              //construct preComponents with arrays for comboBoxs
              String[] EnsembleSizeItems = {" x 1", " x 5", " x 10"};
              String[] RandomizeItems = {"Compare all methods"," Random Features", " Random Sampling", " Randomise Outputs"};
              String[] baseModelItems = {"Nearest Neighbour", "Linear Regression", "M5P Tree"};
              String[] DataItems = {"autoprice", "BreastTumor", "cholesterol", "housing","pollution"};
         String[] EnsembleSizeRun = {" -E 1 -N 5", " -E 5 -N 5", " -E 10 -N 5"};
              String[] RandomizeRun = {""," -S 0"," -S 1"," -S 2"};
         String[] baseModelRun = {"research.predictors.knn",
                                       "weka.classifiers.LinearRegression",
                                       "weka.classifiers.trees.M5P"};
         String[] dataRun = {"-c 16 -t \"C://ensembleResearchNew//data//autoprice.arff\"",
         "-c 10 -t \"C://ensembleResearchNew//data//BreastTumor.arff\"",
         "-c 14 -t \"C://ensembleResearchNew//data//cholesterol.arff\"",
         "-c 14 -t \"C://ensembleResearchNew//data//housing.arff\"",
         "-c 16 -t \"C://ensembleResearchNew//data//pollution.arff\""};
         //construct components
         baseModel = new JComboBox(baseModelItems);
         baseModel.setSelectedIndex(START_INDEX);
         EnsembleSize = new JComboBox (EnsembleSizeItems);
         EnsembleSize.setSelectedIndex(0);
         Randomize = new JComboBox (RandomizeItems);
         Randomize.setSelectedIndex(2);
                   dataChoices = new JComboBox (DataItems);
         dataChoices.setSelectedIndex(0);
         //constructs configurations for running experiment
                   Configs = (baseModelRun[baseModel.getSelectedIndex()] + " "
              + dataRun[dataChoices.getSelectedIndex()]
              + EnsembleSizeRun[EnsembleSize.getSelectedIndex()]
              + RandomizeRun[Randomize.getSelectedIndex()]);
              void constructComponents()
                   //constructs labels
         label1 = new JLabel ("<html><font color=red size=10>MAIN MENU</font></html>");
         label2 = new JLabel ("Select size of ensemble:");
         label3 = new JLabel ("Select a Base Model:");
         label4 = new JLabel ("Select randomising method:");
         label5 = new JLabel ();
         label6 = new JLabel ();
         label7 = new JLabel ("Select data set:");
         //constructs buttons
         Reset = new JButton ("Reset");
         Run = new JButton ("Run!");                
         void addComponents()
         //adds comboBoxs
         add (EnsembleSize);
         add (Randomize);
         add (baseModel);
         add (dataChoices);
         //adds labels
         add (label1);
         add (label2);
         add (label3);
         add (label4);
         add (label5);
         add (label6);
         add (label7);
         //add buttons
         add (Reset);
         add (Run);
         //add message hints to buttons
         Run.setToolTipText("Press this button to run experiment");
         Reset.setToolTipText("Press this button to reset all options for experiment");
              void positionComponents()
         //Sets size and set layout for panel
         setPreferredSize (new Dimension (420, 400));
         setLayout (null);
         sets component bounds for Absolute Positioning of components
         * setup guide = name.setBounds(x1, y, x2, height) *
         //sets positions for combo boxes
         EnsembleSize.setBounds (225, 60, 60, 25);
         Randomize.setBounds (225, 170, 150, 25);
         baseModel.setBounds (225, 115, 137, 25);
         dataChoices.setBounds (225, 225, 150, 25);
         //sets positions for labels on panel
         label1.setBounds (100, 0, 300, 40);
         label2.setBounds (65, 60, 145, 25);
         label3.setBounds (80, 114, 122, 25);
         label4.setBounds (42, 170, 166, 25);
         label5.setBounds (175, 350, 100, 25);//RUNNING NOW!!!
         label6.setBounds (10, 275, 700, 25);//configs
         label7.setBounds (110, 225, 150, 25);
         //sets positions for buttons on panel
         Reset.setBounds (125, 315, 100, 20);
         Run.setBounds (215, 315, 100, 20);
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new JFrame ("JPanel Preview");
         frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().add (new Menu());
         frame.pack();
         frame.setVisible (true);
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Menu extends JPanel implements ActionListener
         private JButton Reset;
         private JButton Run;
         private JLabel label1;
         private JLabel label2;
         private JLabel label3;
         private JLabel label4;
         private JLabel label5;
         private JLabel label6;
         private JLabel label7;
         private JComboBox EnsembleSize = null;
         private JComboBox Randomize;
         private JComboBox baseModel = null;
         private JComboBox dataChoices;
         final static int START_INDEX = 0;
         private String Configs;
         private String[] baseModelRun;
         private String[] dataRun;
         private String[] EnsembleSizeRun;
         private String[] RandomizeRun;
         public Menu()
              constructComboBoxs();
              constructComponents();
              addComponents();
              positionComponents();
    //          Set ActionListeners
              Run.setActionCommand("RunButton");
              Run.addActionListener(this);
              Reset.setActionCommand("ResetButton");
              Reset.addActionListener(this);
              EnsembleSize.setActionCommand("ensemble");
              EnsembleSize.addActionListener(this);
              baseModel.setActionCommand("base");
              baseModel.addActionListener(this);
              Randomize.setActionCommand("random");
              Randomize.addActionListener(this);
              dataChoices.setActionCommand("data");
              dataChoices.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if (e.getActionCommand().equals("RunButton"))
                   label5.setText("<html><font color=red>RUNNING NOW!!!</font></html>");
                   label6.setText("Configs: "+EnsembleSize.getItemAt(EnsembleSize.getSelectedIndex())
              + " - " + baseModel.getItemAt(baseModel.getSelectedIndex()) + " - "
              + Randomize.getItemAt(Randomize.getSelectedIndex()) + " - "
              + dataChoices.getItemAt(dataChoices.getSelectedIndex()));
                   EnsembleSize.setEnabled(false);
                   baseModel.setEnabled(false);
                   Randomize.setEnabled(false);
                   dataChoices.setEnabled(false);
              else if(e.getActionCommand().equals("ResetButton"))
                   Toolkit.getDefaultToolkit().beep();
                   label5.setText("");
                   label6.setText("Configs: ");
                   EnsembleSize.setEnabled(true);
                   baseModel.setEnabled(true);
                   Randomize.setEnabled(true);
                   dataChoices.setEnabled(true);
                   EnsembleSize.setSelectedIndex(0);
                   baseModel.setSelectedIndex(0);
                   Randomize.setSelectedIndex(0);
                   dataChoices.setSelectedIndex(0);
              else if(e.getActionCommand().equals("ensemble"))
              label6.setText("Configs: " + baseModel.getItemAt(baseModel.getSelectedIndex()) + " - "
                                                 + Randomize.getItemAt(Randomize.getSelectedIndex()) + " - "
                                                 + dataChoices.getItemAt(dataChoices.getSelectedIndex()) + " - "
                                                 + EnsembleSize.getItemAt(EnsembleSize.getSelectedIndex()) );
              else if(e.getActionCommand().equals("base"))
              label6.setText("Configs: " + baseModel.getItemAt(baseModel.getSelectedIndex()) + " - "
                                                 + Randomize.getItemAt(Randomize.getSelectedIndex()) + " - "
                                                 + dataChoices.getItemAt(dataChoices.getSelectedIndex()) + " - "
                                                 + EnsembleSize.getItemAt(EnsembleSize.getSelectedIndex()) );
              else if(e.getActionCommand().equals("random"))
              label6.setText("Configs: " + baseModel.getItemAt(baseModel.getSelectedIndex()) + " - "
                                                 + Randomize.getItemAt(Randomize.getSelectedIndex()) + " - "
                                                 + dataChoices.getItemAt(dataChoices.getSelectedIndex()) + " - "
                                                 + EnsembleSize.getItemAt(EnsembleSize.getSelectedIndex()) );
              else if(e.getActionCommand().equals("data"))
              label6.setText("Configs: " + baseModel.getItemAt(baseModel.getSelectedIndex()) + " - "
                                                 + Randomize.getItemAt(Randomize.getSelectedIndex()) + " - "
                                                 + dataChoices.getItemAt(dataChoices.getSelectedIndex()) + " - "
                                                 + EnsembleSize.getItemAt(EnsembleSize.getSelectedIndex()) );
         void constructComboBoxs()
    //          construct preComponents with arrays for comboBoxs
              String[] EnsembleSizeItems = {" x 1", " x 5", " x 10"};
              String[] RandomizeItems = {"Compare all methods"," Random Features", " Random Sampling", " Randomise Outputs"};
              String[] baseModelItems = {"Nearest Neighbour", "Linear Regression", "M5P Tree"};
              String[] DataItems = {"autoprice", "BreastTumor", "cholesterol", "housing","pollution"};
              String[] EnsembleSizeRun = {" -E 1 -N 5", " -E 5 -N 5", " -E 10 -N 5"};
              String[] RandomizeRun = {""," -S 0"," -S 1"," -S 2"};
              String[] baseModelRun = {"research.predictors.knn",
                        "weka.classifiers.LinearRegression",
              "weka.classifiers.trees.M5P"};
              String[] dataRun = {"-c 16 -t \"C://ensembleResearchNew//data//autoprice.arff\"",
                        "-c 10 -t \"C://ensembleResearchNew//data//BreastTumor.arff\"",
                        "-c 14 -t \"C://ensembleResearchNew//data//cholesterol.arff\"",
                        "-c 14 -t \"C://ensembleResearchNew//data//housing.arff\"",
              "-c 16 -t \"C://ensembleResearchNew//data//pollution.arff\""};
    //          construct components
              baseModel = new JComboBox(baseModelItems);
              baseModel.setSelectedIndex(START_INDEX);
              EnsembleSize = new JComboBox (EnsembleSizeItems);
              EnsembleSize.setSelectedIndex(0);
              Randomize = new JComboBox (RandomizeItems);
              Randomize.setSelectedIndex(2);
              dataChoices = new JComboBox (DataItems);
              dataChoices.setSelectedIndex(0);
    //          constructs configurations for running experiment
              Configs = (baseModelRun[baseModel.getSelectedIndex()] + " "
                        + dataRun[dataChoices.getSelectedIndex()]
                        + EnsembleSizeRun[EnsembleSize.getSelectedIndex()]
                        + RandomizeRun[Randomize.getSelectedIndex()]);
         void constructComponents()
    //          constructs labels
              label1 = new JLabel ("<html><font color=red size=10>MAIN MENU</font></html>");
              label2 = new JLabel ("Select size of ensemble:");
              label3 = new JLabel ("Select a Base Model:");
              label4 = new JLabel ("Select randomising method:");
              label5 = new JLabel ();
              label6 = new JLabel ();
              label7 = new JLabel ("Select data set:");
    //          constructs buttons
              Reset = new JButton ("Reset");
              Run = new JButton ("Run!");
         void addComponents()
    //adds comboBoxs
              add (EnsembleSize);
              add (Randomize);
              add (baseModel);
              add (dataChoices);
    //adds labels
              add (label1);
              add (label2);
              add (label3);
              add (label4);
              add (label5);
              add (label6);
              add (label7);
    //add buttons
              add (Reset);
              add (Run);
    //add message hints to buttons
              Run.setToolTipText("Press this button to run experiment");
              Reset.setToolTipText("Press this button to reset all options for experiment");
         void positionComponents()
    //          Sets size and set layout for panel
              setPreferredSize (new Dimension (420, 400));
              setLayout (null);
              sets component bounds for Absolute Positioning of components
              * setup guide = name.setBounds(x1, y, x2, height) *
    //sets positions for combo boxes
              EnsembleSize.setBounds (225, 60, 60, 25);
              Randomize.setBounds (225, 170, 150, 25);
              baseModel.setBounds (225, 115, 137, 25);
              dataChoices.setBounds (225, 225, 150, 25);
    //sets positions for labels on panel
              label1.setBounds (100, 0, 300, 40);
              label2.setBounds (65, 60, 145, 25);
              label3.setBounds (80, 114, 122, 25);
              label4.setBounds (42, 170, 166, 25);
              label5.setBounds (175, 350, 100, 25);//RUNNING NOW!!!
              label6.setBounds (10, 275, 700, 25);//configs
              label7.setBounds (110, 225, 150, 25);
    //sets positions for buttons on panel
              Reset.setBounds (125, 315, 100, 20);
              Run.setBounds (215, 315, 100, 20);
         public static void main(String[] args)
              JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame ("JPanel Preview");
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add (new Menu());
              frame.pack();
              frame.setVisible (true);
    Right here is my updated code at present when run button is clicked outputs all selected values to label at bottom of GUI. But I need it to output the relevant value from another array
    say if 2nd item 2x 5" EnsembleSize ComboBox is selected
    I want it not to output that to label but the 2nd item in the array EnsembleSizeRun so instead it should output "-E 5 - N 5"
    If we can get that one to do that then it will be very easy to do the same for all the others, Can anyone get that to work?

  • [svn:fx-trunk] 11737: ComboBox and DropDownList bug fixes

    Revision: 11737
    Author:   [email protected]
    Date:     2009-11-12 13:25:33 -0800 (Thu, 12 Nov 2009)
    Log Message:
    ComboBox and DropDownList bug fixes
    SDK-23635 - Implement type-ahead in DropDownList
    Added code in DropDownListBase keyDownHandler to listen for letters and change the selection if there is a match. At some point, we should modify findKey and findString (I'll file an ECR for that). For now, I've just overridden findKey and cobbled together the logic from List.findKey and List.findString. In ComboBox, we override findKey to do nothing since ComboBox has its own logic that relies on textInput changes.
    SDK-23859 - DropDownList does not reset caretIndex when selection is cleared
    Fixed this in two places. In ComboBox.keyDownHandlerHelper, we update the caret index when ESC is pressed. In DropDownListBase.dropDownController_closeHandler, we update the caret index if the commit has been canceled (ie. ESC was pressed).
    SDK-24175 - ComboBox does not select an item with ENTER when openOnInput = false
    When the ComboBox was closed and the arrow keys were pressed, the selectedIndex was changed. When ENTER was pressed, it was committing actualProposedSelectedIndex, not selectedIndex. The fix is to override the selectedIndex setter to keep actualProposedSelectedIndex in sync if selectedIndex was changed. Usually it is kept in sync when the dropDown is opened.
    SDK-24174 - ComboBox does not scroll correctly when openOnInput = false
    When typing in a match, the caretIndex was changed, but not the selectedIndex (because matching when it is closed doesn't commit the value until you press ENTER or lose focus). When closed, the navigation keys were changing the selectedIndex relative to the previous selectedIndex. I updated this to change relative to caretIndex instead. In most cases, caretIndex and selectedIndex are equivalent while the dropDown is closed.
    Other changes:
    - Replaced some calls to dropDownController.isOpen with isDropDownOpen.
    - Added protection RTE protection to ComboBox.changeHighlightedSelection
    QE notes: None
    Doc notes: None
    Bugs: SDK-23635, SDK-23859, SDK-24175, SDK-24174
    Reviewer: Deepa
    Tests run: ComboBox, DropDownList
    Is noteworthy for integration: No
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23635
        http://bugs.adobe.com/jira/browse/SDK-23859
        http://bugs.adobe.com/jira/browse/SDK-24175
        http://bugs.adobe.com/jira/browse/SDK-24174
        http://bugs.adobe.com/jira/browse/SDK-23635
        http://bugs.adobe.com/jira/browse/SDK-23859
        http://bugs.adobe.com/jira/browse/SDK-24175
        http://bugs.adobe.com/jira/browse/SDK-24174
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/ComboBox.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/DropDownListBase.as

    This bug figures out also when creating a custom spark ComboBox, then trying to programatically update the userProposedSelectedIndex property. The proposed selected index is selected, but does not apply the same skin as when mouse is on rollover or item is selected due to up and down keys.
    The issue seems like updating the status of the item renderer to rollover or selected to get the same skin applied.
    Please could you attach DropDow nList.as that you edited ?
    Thank you so much.

  • Icons(images in Combobox) read from folder in project

    Hi everyone,
    I'm trying to populate these icons (images) from the img folder under my project. Most of these icons are in .png format and I want to populate them into the ComboBox which i have. On top of that, when the user selects one of the icons from the ComboBox, I need to show the icon on the ComboBox which now I'm only able to show the label that is being tagged to it. I saw the IconComboBox.as example but I can't apply them to my current design.
    Is there a way to achieve it?
    My codes for the CheckBoxes and ComboBoxes:
    <mx:Panel id="layerPanel" backgroundColor="#ffffff" height="220" width="220"
      title="Layer Control Manager" showEffect="WipeRight" hideEffect="WipeLeft"
      horizontalScrollPolicy="off" verticalScrollPolicy="off">
      <mx:VBox height="140" width="400" horizontalScrollPolicy="off">
       <mx:List id="layerList" itemClick="layerList_changeHandler(event)"
       alternatingItemColors="[#EEEEEE, white]" selectable="true"
       dataProvider="{lstDataProvider}" labelField="name" height="190" verticalScrollPolicy="off">
       <mx:itemRenderer>
        <mx:Component>
         <mx:HBox>
          <mx:CheckBox id="chkBox" change="layerCheckBox_onChange(event);">
          <mx:Script>
          <![CDATA[
          import mx.controls.Alert;
          import mx.events.FlexEvent;
          override public function set data(value:Object):void
           super.data = value;
           if(value != null)
            chkBox.selected = value.isSelected;
            if(!chkBox.selected)
             comboBox.selectedIndex = -1;
             comboBox.prompt = "Please Select";        
             comboBox.enabled = false;
          private function layerCheckBox_onChange(evt:Event):void
           data.isSelected = !data.isSelected;
           if(data.isSelected)
            comboBox.enabled = true;
           else
            comboBox.enabled = false;
           if(data.isSelected && comboBox.selectedIndex > -1)
            this.dispatchEvent(new Event("addImageToApplication", true));
          ]]>
          </mx:Script>
          </mx:CheckBox>
          <mx:Label text="{data.label}" />
          <mx:ComboBox id="comboBox" enabled="false" width="100%" change="onComboBoxChange(event)" dataProvider="{outerDocument.comboBoxArray}" prompt="Please Select">
           <mx:Script>
            <![CDATA[
             import mx.controls.ComboBox;
             private function onComboBoxChange(evt:Event):void
              var myCombo:ComboBox = evt.currentTarget as ComboBox;
              //if(data.label == myCombo.selectedItem.label)
               outerDocument.comboImageUrl = myCombo.selectedItem.src;
               if(data.isSelected)
                this.dispatchEvent(new Event("addImageToApplication", true));
            ]]>
            </mx:Script>
           <mx:itemRenderer>
            <mx:Component>
             <mx:HBox horizontalScrollPolicy="off">
              <mx:Image source="{data.src}" width="20" height="20" maintainAspectRatio="false" />
              <mx:Label text="{data.label}" />
             </mx:HBox>
            </mx:Component>
           </mx:itemRenderer>
          </mx:ComboBox>
         </mx:HBox>
        </mx:Component>
       </mx:itemRenderer>
       </mx:List>
      </mx:VBox>
    <mx:VBox top="165" left="30">
      <mx:Button label="Reset List" width="160" id="resetBut" click="resetList()"/>
    </mx:VBox>
    </mx:Panel>

    http://blogs.adobe.com/aharui/2007/04/icons_in_combobox.html
    This didn't work for you?
    - Jason

  • ComboBox and Array setSelectedIndex

    Hi all,
    I have created a combo box which gets its items from an array:
         String[] crustType = { "Select a Crust", "Thin", "Double Dough", "Stuffed" };
         JComboBox crustList = new JComboBox( crustType );Now I want to reset this combo box from a different class file. (I know this is kind of obvious but keep in mind that "pizzeria" is an object of the application and "pInfo" is an object of PizzaInfo which contains the above code for the JComboBox. I've tried things like:
    pizzeria.pInfo.crustList.setSelectedIndex( crustType[ 0 ] );
    pizzeria.pInfo.crustList.setSelectedIndex( 0 );and all other sorts of combination of code. I guess I'm just not sure how to reset it to the original index of 0 in the array.

    I've searched the APIs and I'm wondering if the only way to change or reset the combo box is to originally set it up by setting it up this way
    comboBox.addItem(makeObj("Item 1"));
    comboBox.addItem(makeObj("Item 1"));
    and using
    setSelectedItem( "Item 1")
    to reset it.

  • DataGrid dropdowns getting reset on scrolling through the grid

    I have a datagrid which contains two columns with dropdowns.
    The dropdown values are set to particular index programmatically.
    But when the scroll bar of the grid is made to scroll from top to
    bottom and then back to top the selected values get reset. Any idea
    about this behaviour?

    Yes. item renderers are "recycled". Flex only creates enough
    for the visible rows. When you scroll, the item data for the
    scrolled-into position item is sent to the renderer(through the set
    data() setter), which must use that data to render its visible
    state.
    This means all aspects of the item renderer must be data
    driven. You cannot do an data oriented work in initialize or
    creation complete, but must override the set data() method. Best
    practice is actually a bit more complicated thatn that. You will
    have toset the selectedIndex of the renderer combobox from some
    value stored in the item.
    Google: Alex Harui item renderer recycle
    For a full explanation and examples.
    Tracy

  • Did ComboBox change in the recent JavaFX releases?

    Hi there.
    I use a ComboBox to display the gender of a person. Now recently we discovered a bug, and I am pretty sure it used to work in a previous version. I also updated my JDK recently to 7u13 ( JavaFX 2.2.5) and maybe some others did too.
    The following use case should work (and even worked in my opinion), but doesn't anymore.
    Run the code. (Gender is initialized with null)
    Click the Chose Male Button.
    Male is selected in the ComboBox.
    Click Reset.
    Click Male.
    Nothing happens! I expected that Male is again selected.
    Can someone comment on this issue please?
    import javafx.application.Application;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.collections.FXCollections;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ComboBox;
    import javafx.scene.layout.VBoxBuilder;
    import javafx.stage.Stage;
    public class TestApp2 extends Application {
        public static void main(String[] args) {
            Application.launch();
        private ObjectProperty<Gender> gender = new SimpleObjectProperty<Gender>();
        @Override
        public void start(Stage stage) throws Exception {
            ComboBox<Gender> comboBox = new ComboBox<Gender>();
            comboBox.setItems(FXCollections.observableArrayList(Gender.values()));
            comboBox.valueProperty().bindBidirectional(gender);
            Button button = new Button("Reset");
            button.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent actionEvent) {
                    gender.set(null);
            Button buttonSetMale = new Button("Set Male");
            buttonSetMale.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent actionEvent) {
                    gender.set(Gender.MALE);
            Scene scene = new Scene(VBoxBuilder.create().children(comboBox, button, buttonSetMale).build());
            stage.setScene(scene);
            stage.show();
        public enum Gender {
            MALE,
            FEMALE,
            UNKNOWN
    }

    This is a known bug and is fixed in JavaFX 8.0. You can see the bug report here:
    http://javafx-jira.kenai.com/browse/RT-27654
    -- Jonathan

Maybe you are looking for