Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting string value from JComboBox in java

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.

like image 338
NOOBprogrammer Avatar asked May 19 '26 22:05

NOOBprogrammer


2 Answers

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

like image 97
mKorbel Avatar answered May 21 '26 21:05

mKorbel


The error is a NullPointerException. It it thrown here if (genderJCB.getSelectedItem().equals("female")){. This occurs because genderJCB is null. Why is this? Didn't you set it here JComboBox genderJCB= new JComboBox(test);? No. You made a new local variable, rather than a field, so you never declared the field.

like image 37
Alex Coleman Avatar answered May 21 '26 19:05

Alex Coleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!