Getting string value from JComboBox in java

debugging, java, jcombobox, swing

Solution

i also tried the combo.getEditor().getItem() but it did not work.

your most important issue is, that you declare variable that never used or initalized

private JComboBox genderJCB;

because inside public `TestJCB(){` overrode and created

JComboBox genderJCB = new JComboBox(test);// same issue with JLabel too

if you want to listenening in `ActionPerformed`, then to change that to

genderJCB = new JComboBox(test);

better could be to read JComboBox tutorial

Problem

I'm doing a testJComboBox program. Once I select the outputs of the jCombobox, I would get the string value that I need. However, it doesn't work. Here's my code: ``` import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TestJCB extends JFrame { private JLabel genderL; private JComboBox genderJCB; private String[] test = {"male", "female"}; private JButton gB; public TestJCB() { setSize(400, 400); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); setVisible(true); JPanel frame = new JPanel(); frame.setSize(400, 400); frame.setLocation(0, 0); frame.setLayout(null); frame.setVisible(true); JLabel genderL = new JLabel("Gender"); genderL.setBounds(10, 200, 100, 30); JComboBox genderJCB = new JComboBox(test); genderJCB.setBounds(60, 10, 100, 30); JButton gB = new JButton("Gender"); gB.setBounds(10, 50, 60, 30); aaa a = new aaa(); gB.addActionListener(a); frame.add(genderL); frame.add(genderJCB); frame.add(gB); add(frame); } public class aaa implements ActionListener { public void actionPerformed(ActionEvent sHandler) { if (genderJCB.getSelectedItem().equals("female")) { System.out.print("yes"); } else { System.out.print("no"); } } } public static void main(String[] args) { TestJCB test = new TestJCB(); test.setVisible(true); } } ``` I also tried `combo.getEditor().getItem()` but it did not work.

Original source