add JTextPane string to JComboBox

I have looked at similar questions on this site but I cannot seem to grasp the concept, so I have to post my own question to get an answer specific to me.

I am trying to get the text entered into the JTextField txtAddEng added to the JComboBox engBox by clicking the JButton btnAdd.

    engBox = new JComboBox();
    engBox.setMaximumRowCount(1000);
    engBox.setModel(new DefaultComboBoxModel(new String[] {"Select an Engagement"}));
    engBox.setBounds(10, 0, 181, 20);       
    sopPanel.add(engBox);

    txtAddEng = new JTextField();
    txtAddEng.setHorizontalAlignment(SwingConstants.CENTER);
    txtAddEng.setToolTipText("Type ENG-#### and click Add");
    txtAddEng.setText("Add an engagement?");
    txtAddEng.setBounds(201, 0, 181, 20);
    sopPanel.add(txtAddEng);
    txtAddEng.setColumns(10);

    JButton btnAdd = new JButton("Add");
    btnAdd.setBounds(383, 3, 51, 17);
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent clickAdd) {
            txtAddEng.toString();
            engBox.add(txtAddEng);
        }
    });
728x90

1 Answers add JTextPane string to JComboBox

txtAddEng.toString();

That statement does nothing. It just invokes the toString() method but never assigns it to a variable. Get rid of that statement.

engBox.add(txtAddEng);

You don't want to add the text field to the combo box. You want to add the text in the text field the to model of the combo box.

So the code should be;

engBox.addItem( txtAddEng.getText() );

Read the section from the Swing tutorial on How to Use Combo Boxes for more information and working examples. Keep a link to the tutorial handy for all Swing basics.

8 months ago