Jeremy Blume
Jeremy Blume

Reputation: 3

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);
        }
    });

Upvotes: 0

Views: 33

Answers (1)

camickr
camickr

Reputation: 324118

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.

Upvotes: 1

Related Questions