Search code examples
javaswingjlabeljtextfieldjcombobox

Swing: jlabel+jcombox+jtextfield


I need to build a jlabel next to a jcombobox next to a jtextfield. JTextfield must be accepting only numbers. The text from jtextfield should be stored in a string and the element chosen also stored in a different string. Also it would be ideal if i could add a jbutton so that all the selections to be parsed when the button is clicked. I am currently using this unfinished code, but it wont work. Can someone suggest the required additions? Thanks in advance

   public class constraints {

            private static JTextField tField;
            private MyDocumentFilter documentFilter;
            private JLabel amountLabel;
            private static String amountString = "Select Quantity (in ktones): ";
            public static String str = "" ;

            private void displayGUI()
            {
                JFrame frame = new JFrame("Constraints");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                amountLabel = new JLabel(amountString);

                JPanel contentPane = new JPanel();
                contentPane.setBorder(
                    BorderFactory.createEmptyBorder(5, 5, 5, 5));
                tField = new JTextField(10);

                amountLabel.setLabelFor(tField);

                String[] petStrings = { "Less", "Equal", "More"};
                JComboBox petList = new JComboBox(petStrings) ;
                        petList.setSelectedIndex(3);
                    petList.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {

                             JComboBox cb = (JComboBox)event.getSource();
                             String petName = (String)cb.getSelectedItem();

                            System.out.println("petName");
                        }
                    });                         

                ((AbstractDocument)tField.getDocument()).setDocumentFilter(
                        new MyDocumentFilter());        
                contentPane.add(amountLabel);
                  contentPane.add(petList);
                contentPane.add(tField); 


                frame.setContentPane(contentPane);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }

            public static void main(String[] args)
            {
                Runnable runnable = new Runnable()
                {
                    @Override
                    public void run()
                    {
                        new constraints().displayGUI();
                    }
                };
                EventQueue.invokeLater(runnable);

            }
        }

        class MyDocumentFilter extends DocumentFilter
        {   
            @Override
            public void insertString(DocumentFilter.FilterBypass fp
                    , int offset, String string, AttributeSet aset)
                                        throws BadLocationException
            {
                int len = string.length();
                boolean isValidInteger = true;

                for (int i = 0; i < len; i++)
                {
                    if (!Character.isDigit(string.charAt(i)))
                    {
                        isValidInteger = false;
                        break;
                    }
                }
                if (isValidInteger)
                    super.insertString(fp, offset, string, aset);
                else
                    Toolkit.getDefaultToolkit().beep();
            }

            @Override
            public void replace(DocumentFilter.FilterBypass fp, int offset
                            , int length, String string, AttributeSet aset)
                                                throws BadLocationException
            {
                int len = string.length();
                boolean isValidInteger = true;

                for (int i = 0; i < len; i++)
                {
                    if (!Character.isDigit(string.charAt(i)))
                    {
                        isValidInteger = false;
                        break;
                    }
                }
                if (isValidInteger)
                    super.replace(fp, offset, length, string, aset);
                else
                    Toolkit.getDefaultToolkit().beep();
            }
        }

Solution

  • Couple of things:

    String[] petStrings = { "Less", "Equal", "More"};
    JComboBox petList = new JComboBox(petStrings);
    petList.setSelectedIndex(3);

    This will throw java.lang.IllegalArgumentException: setSelectedIndex: 3 out of bounds because your JComboBox has only 3 items (index starts in 0).

    String petName = (String)cb.getSelectedItem();
    System.out.println("petName");

    This will always print "petName" string. I think you want:

    System.out.println(petName);
    

    Anyway I think you would want to use ItemListener instead ActionListener:

    petList.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent event) {
            JComboBox cb = (JComboBox)event.getSource();
            String petName = (String) cb.getSelectedItem();
            System.out.println(petName);
        }
    });
    

    Update

    I need to only do that when a jbutton is clicked or enter. Is that possible?

    Yes it is. Just make your JComboBox final and add a JButton to your JPanel:

    final JComboBox petList = new JComboBox(petStrings);
    petList.setSelectedIndex(2);
    
    JButton submit = new JButton("Submit");
    submit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String petName = (String) petList.getSelectedItem();
            System.out.println(petName);
        }
    });
    

    PS: note if you don't make petList final it won't be accessible within the JButton's ActionListener