0

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);
        }
    });
  • What do you mean? You mean transferring text label from JTextField to one of JComboBox item label? – Joe Vanjik Aug 29 '18 at 18:21
  • Yes. So JComboBox defaults to "Select an engagement" but there are no items listed under that. I want to have the JTextPane made so that I can type "Eng-####" and then click the JButton and it will then add what was typed to the JComboBox under "Select an engagement" – Jeremy Blume Aug 29 '18 at 18:23

1 Answers1

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

camickr
  • 321,443
  • 19
  • 166
  • 288