Joption acting like it's in a for loop

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • 4

46 Replies - 1631 Views - Last Post: 04 February 2018 - 10:37 AM Rate Topic: -----

#31 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 22 January 2018 - 11:17 AM

Got ya but still its acting like a loop for some reason,this is driving me crazy.

package test;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;

/**
 *
 * @author ViSion
 */
public class Test {

    public static class SearchContactGui {

        JFrame searchContactFrame;
        JPanel pnl_top, pnl_topLeft, pnl_topCenter, pnl_left, pnl_search;
        JList l_names;
        JScrollPane scrollPane;
        JLabel lbl_searchContact, lbl_search;
        JTextField tf_search;
        ArrayList<String> matchedNames, matchedNumber, contactsNames;
        KeyListener key;
        JOptionPane pane = new JOptionPane();
        int cntr = 1;

        SearchContactGui() {

            searchContactFrame = new JFrame("number book");
            pnl_top = new JPanel();

            lbl_searchContact = new JLabel("Search for Contact");
            lbl_searchContact.setFont(new Font("Arial", Font.BOLD, 25));
            lbl_searchContact.setForeground(Color.blue);
            pnl_top.add(lbl_searchContact, BorderLayout.NORTH);

            pnl_left = new JPanel();
            pnl_left.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            pnl_search = new JPanel();
            lbl_search = new JLabel("Search");
            tf_search = new JTextField(18);
            pnl_search.add(lbl_search);
            pnl_search.add(tf_search);
            pnl_left.add(pnl_search, c);
            c.anchor = GridBagConstraints.EAST;
            c.gridx = 0;
            c.gridy = 1;
            c.insets = new Insets(20, 0, 0, 9);

            contactsNames = new ArrayList<String>();
            contactsNames.add("bernard");
            contactsNames.add("brandon");
            contactsNames.add("ben");

            Collections.sort(contactsNames);
            l_names = new JList(contactsNames.toArray());
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(l_names);
            scrollPane.setPreferredSize(new Dimension(200, 150));
            pnl_left.add(scrollPane, c);

            searchContactFrame.add(pnl_top, BorderLayout.NORTH);
            searchContactFrame.add(pnl_left, BorderLayout.WEST);
            searchContactFrame.pack();
            searchContactFrame.setVisible(true);
            searchContactFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            tf_search.addKeyListener(key = new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {

                }

                @Override
                public void keyPressed(KeyEvent e) {

                }

                @Override
                public void keyReleased(KeyEvent e) {

                    if (cntr++ % 2 != 0) {
                        return;
                    }
                    
                   else if (e.getKeyCode() != KeyEvent.VK_ENTER) {

                        matchedNumber = new <String>ArrayList();
                        matchedNames = new <String>ArrayList();

                        for (int j = 0; j < contactsNames.size(); j++) {
                            if (contactsNames.get(j).length() >= tf_search.getText().length()) {

                                if (contactsNames.get(j).substring(0, tf_search.getText().length()).equals(tf_search.getText())) {
                                    matchedNames.add(contactsNames.get(j));

                                }
                            }
                        }
                        Collections.sort(matchedNames);
                        l_names = new JList(matchedNames.toArray());
                        scrollPane.setViewportView(l_names);

                    } else {
                        l_names.requestFocus();
                        l_names.setSelectedIndex(0);

                        l_names.addKeyListener(new KeyListener() {
                            @Override
                            public void keyTyped(KeyEvent e) {

                            }

                            @Override
                            public void keyPressed(KeyEvent e) {
                                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane pane = new JOptionPane();

                                    if(l_names.isSelectionEmpty()){
                                        System.out.println("no selection");
                                        
                                    }
                                    else{
                                int    input = pane.showOptionDialog(searchContactFrame, l_names.getSelectedValue().toString(), "title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);

                                    if (input == JOptionPane.OK_OPTION) {

                                        System.out.println("ok");
                                        l_names.clearSelection();
                                        tf_search.requestFocus();
                                        
                                    }
                                }}
                            }

                            @Override
                            public void keyReleased(KeyEvent e) {

                                //pane.requestFocus();
                            }

                        });
                    }

                }
            });

        }
    }

    public static void main(String[] args) {
        new SearchContactGui();
    }

}



try this code and try selecting names for 3 or 4 times check the output.
Was This Post Helpful? 0
  • +
  • -

#32 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 660
  • View blog
  • Posts: 4,981
  • Joined: 25-December 13

Re: Joption acting like it's in a for loop

Posted 22 January 2018 - 11:27 AM

My code has the cntr testing code in the method with the JOptionPane about line 135.

There is a lot of sloppy alignment in this version of the code making it harder to read.

This post has been edited by NormR: 22 January 2018 - 11:28 AM

Was This Post Helpful? 0
  • +
  • -

#33 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 22 January 2018 - 11:46 AM

ok i managed to make it work but i don' t know why without
if (cntr++ % 2 != 0) {
                        return;
                    }

the second listener won't work

that's my final code that works great but didn't understand why :)

package test;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;

/**
 *
 * @author ViSion
 */
public class Test {

    public static class SearchContactGui {

        JFrame searchContactFrame;
        JPanel pnl_top, pnl_topLeft, pnl_topCenter, pnl_left, pnl_search;
        JList l_names;
        JScrollPane scrollPane;
        JLabel lbl_searchContact, lbl_search;
        JTextField tf_search;
        ArrayList<String> matchedNames, matchedNumber, contactsNames;
        KeyListener key,k;
        JOptionPane pane = new JOptionPane();
        int cntr = 1;

        SearchContactGui() {

            searchContactFrame = new JFrame("number book");
            pnl_top = new JPanel();

            lbl_searchContact = new JLabel("Search for Contact");
            lbl_searchContact.setFont(new Font("Arial", Font.BOLD, 25));
            lbl_searchContact.setForeground(Color.blue);
            pnl_top.add(lbl_searchContact, BorderLayout.NORTH);

            pnl_left = new JPanel();
            pnl_left.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            pnl_search = new JPanel();
            lbl_search = new JLabel("Search");
            tf_search = new JTextField(18);
            pnl_search.add(lbl_search);
            pnl_search.add(tf_search);
            pnl_left.add(pnl_search, c);
            c.anchor = GridBagConstraints.EAST;
            c.gridx = 0;
            c.gridy = 1;
            c.insets = new Insets(20, 0, 0, 9);

            contactsNames = new ArrayList<String>();
            contactsNames.add("bernard");
            contactsNames.add("brandon");
            contactsNames.add("ben");

            Collections.sort(contactsNames);
            l_names = new JList(contactsNames.toArray());
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(l_names);
            scrollPane.setPreferredSize(new Dimension(200, 150));
            pnl_left.add(scrollPane, c);

            searchContactFrame.add(pnl_top, BorderLayout.NORTH);
            searchContactFrame.add(pnl_left, BorderLayout.WEST);
            searchContactFrame.pack();
            searchContactFrame.setVisible(true);
            searchContactFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            tf_search.addKeyListener(key = new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {

                }

                @Override
                public void keyPressed(KeyEvent e) {

                }

                @Override
                public void keyReleased(KeyEvent e) {
              if (cntr++ % 2 != 0) {
                        return;
                    }
                    
                    
                   if (e.getKeyCode() != KeyEvent.VK_ENTER) {

                        matchedNumber = new <String>ArrayList();
                        matchedNames = new <String>ArrayList();

                        for (int j = 0; j < contactsNames.size(); j++) {
                            if (contactsNames.get(j).length() >= tf_search.getText().length()) {

                                if (contactsNames.get(j).substring(0, tf_search.getText().length()).equals(tf_search.getText())) {
                                    matchedNames.add(contactsNames.get(j));

                                }
                            }
                        }
                        Collections.sort(matchedNames);
                        l_names = new JList(matchedNames.toArray());
                        scrollPane.setViewportView(l_names);

                    }
                   else{
                        l_names.requestFocus();
                        l_names.setSelectedIndex(0);
                       
                   }}
            });
                       

                        l_names.addKeyListener(k=new KeyListener() {
                            @Override
                            public void keyTyped(KeyEvent e) {

                            }

                            @Override
                            public void keyPressed(KeyEvent e) {
                  
                            }
                            

                            @Override
                            public void keyReleased(KeyEvent e) {
                              if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane pane = new JOptionPane();

                                    
                                int    input = pane.showOptionDialog(searchContactFrame, l_names.getSelectedValue().toString(), "title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);

                                    if (input == JOptionPane.OK_OPTION) {

                                        System.out.println("ok");
                                        l_names.clearSelection();
                                        tf_search.requestFocus();
                                        
                                    }
                                }}
                            

                        });
                    }

            

        }
    

    public static void main(String[] args) {
        new SearchContactGui();
    }

}


Was This Post Helpful? 0
  • +
  • -

#34 ndc85430  Icon User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 710
  • View blog
  • Posts: 2,888
  • Joined: 13-June 14

Re: Joption acting like it's in a for loop

Posted 22 January 2018 - 10:54 PM

Lines 106 and 107 are incorrect. The type parameter comes after the class name (i.e. new ArrayList<String>()). I'm not sure why the parser doesn't complain that the syntax is invalid, though. I suspect that what's happening is you're actually creating an ArrayList without a type parameter (so that all its elements will be of type Object), but it works as you expect because you specify the type of the references correctly. Still, it's best to put the type parameter in the right place, though, to avoid any problems. Having said that, it's perfectly legal to use an empty pair of angle brackets on the right hand side (also known as the "diamond operator"), since the type is specified on the left, e.g. List<String> strings = new ArrayList<>();.

Also, some of your names are using the wrong conventions for Java: you're using underscores rather than camel case. Underscores are usually only used for constants (and often, actually, in test method names because that's a bit easier to read than camel case).

This post has been edited by ndc85430: 23 January 2018 - 02:22 AM

Was This Post Helpful? 1
  • +
  • -

#35 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 27 January 2018 - 07:23 AM

I though it worked well but no it still have problems this is getting me crazy can't seem to find any solution to make it work as expected.

edit:i tried on an even simplier example well moving it to key pressed instead of key released fixed the issue, i'll try it later on my example i posted here then on my main program and let you know how things go.

This post has been edited by ViSion91: 27 January 2018 - 08:25 AM

Was This Post Helpful? 0
  • +
  • -

#36 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 10:54 AM

So now i managed to make it work , but for some reason after 4 selections i get a null pointer exception any idea whats still wrong ?

package key;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.*;

/**
 *
 * @author ViSion
 */
public class Key {

    public static class SearchContactGui {

        JFrame searchContactFrame;
        JPanel pnl_top, pnl_topLeft, pnl_topCenter, pnl_left, pnl_search;
        JList l_names;
        JScrollPane scrollPane;
        JLabel lbl_searchContact, lbl_search;
        JTextField tf_search;
        ArrayList<String> matchedNames, matchedNumber, contactsNames;
        KeyListener key, k;
        JOptionPane pane = new JOptionPane();
        int cntr = 1;
        int cntr2 = 1;

        SearchContactGui() {

            searchContactFrame = new JFrame("number book");
            pnl_top = new JPanel();

            lbl_searchContact = new JLabel("Search for Contact");
            lbl_searchContact.setFont(new Font("Arial", Font.BOLD, 25));
            lbl_searchContact.setForeground(Color.blue);
            pnl_top.add(lbl_searchContact, BorderLayout.NORTH);

            pnl_left = new JPanel();
            pnl_left.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            pnl_search = new JPanel();
            lbl_search = new JLabel("Search");
            tf_search = new JTextField(18);
            pnl_search.add(lbl_search);
            pnl_search.add(tf_search);
            pnl_left.add(pnl_search, c);
            c.anchor = GridBagConstraints.EAST;
            c.gridx = 0;
            c.gridy = 1;
            c.insets = new Insets(20, 0, 0, 9);

            contactsNames = new ArrayList<String>();
            contactsNames.add("bernard");
            contactsNames.add("beca");
            contactsNames.add("bernard");
            contactsNames.add("brandon");
            contactsNames.add("ben");

            Collections.sort(contactsNames);
            l_names = new JList(contactsNames.toArray());
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(l_names);
            scrollPane.setPreferredSize(new Dimension(200, 150));
            pnl_left.add(scrollPane, c);

            searchContactFrame.add(pnl_top, BorderLayout.NORTH);
            searchContactFrame.add(pnl_left, BorderLayout.WEST);
            searchContactFrame.pack();
            searchContactFrame.setVisible(true);
            searchContactFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            tf_search.addKeyListener(key = new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {

                }

                @Override
                public void keyPressed(KeyEvent e) {

                }

                @Override
                public void keyReleased(KeyEvent e) {
                    System.out.println("cntr" + cntr);
                    if (e.getKeyCode() != KeyEvent.VK_ENTER) {

                        matchedNumber = new <String>ArrayList();
                        matchedNames = new <String>ArrayList();

                        for (int j = 0; j < contactsNames.size(); j++) {
                            if (contactsNames.get(j).length() >= tf_search.getText().length()) {

                                if (contactsNames.get(j).substring(0, tf_search.getText().length()).equals(tf_search.getText())) {
                                    matchedNames.add(contactsNames.get(j));

                                }
                            }
                        }
                        Collections.sort(matchedNames);
                        l_names = new JList(matchedNames.toArray());
                        scrollPane.setViewportView(l_names);

                    } else {
                        if (cntr++ % 2 == 0) {
                            return;
                        } else {
                            l_names.requestFocus();
                            l_names.setSelectedIndex(0);
                        }
                        l_names.addKeyListener(k = new KeyListener() {
                            @Override
                            public void keyTyped(KeyEvent e) {

                            }

                            @Override
                            public void keyPressed(KeyEvent e) {

                            }

                            @Override
                            public void keyReleased(KeyEvent e) {
                                System.out.println("cntr2" + cntr2);
                                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                                    if (cntr2++ % 2 == 0) {
                                        return;
                                    } else {

                                        JOptionPane pane = new JOptionPane();
                                        System.out.println(l_names.getSelectedValue().toString());

                                        int input = pane.showOptionDialog(searchContactFrame, l_names.getSelectedValue().toString(), "title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);

                                        if (input == JOptionPane.OK_OPTION) {

                                            System.out.println("ok");
                                            l_names.clearSelection();
                                            tf_search.requestFocus();

                                        }
                                    }
                                }

                            }

                        });

                    }
                }

            });

        }

    }

    public static void main(String[] args) {
        new SearchContactGui();
    }

}


Was This Post Helpful? 0
  • +
  • -

#37 ndc85430  Icon User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 710
  • View blog
  • Posts: 2,888
  • Joined: 13-June 14

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 10:57 AM

There's a lot of code there. What have you done to debug what's causing the problem?
Was This Post Helpful? 0
  • +
  • -

#38 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 11:07 AM

well i know that the problem is that on the 4th selection l_names.getSelectedValue() is null for some reason but why this is happening i have no idea.
Was This Post Helpful? 0
  • +
  • -

#39 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 660
  • View blog
  • Posts: 4,981
  • Joined: 25-December 13

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 11:10 AM

Quote

on the 4th selection l_names.getSelectedValue() is null for some reason but why this is happening

Add some print statements to show the state of the variables used in the code.
For example what is the value of l_names and how many values does it have on the line before getSelectedValue() is called.
Was This Post Helpful? 0
  • +
  • -

#40 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 11:14 AM

run:
beca
ok
beca
ok
beca
ok
beca
ok
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at key.Key$SearchContactGui$1$1.keyReleased(Key.java:136)
	at java.awt.AWTEventMulticaster.keyReleased(AWTEventMulticaster.java:260)
	at java.awt.AWTEventMulticaster.keyReleased(AWTEventMulticaster.java:259)
	at java.awt.Component.processKeyEvent(Component.java:6494)
	at javax.swing.JComponent.processKeyEvent(JComponent.java:2832)
	at java.awt.Component.processEvent(Component.java:6310)
	at java.awt.Container.processEvent(Container.java:2236)
	at java.awt.Component.dispatchEventImpl(Component.java:4889)
	at java.awt.Container.dispatchEventImpl(Container.java:2294)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
	at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806)
	at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074)
	at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945)
	at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771)
	at java.awt.Component.dispatchEventImpl(Component.java:4760)
	at java.awt.Container.dispatchEventImpl(Container.java:2294)
	at java.awt.window.dispatchEventImpl(window.java:2746)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.awt.EventQueue$4.run(EventQueue.java:729)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)



this is what happened when i chose beca 4 times
Was This Post Helpful? 0
  • +
  • -

#41 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 660
  • View blog
  • Posts: 4,981
  • Joined: 25-December 13

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 11:29 AM

What variable has the null value?
How many items are in the l_names list when getSelectedValue is called?
Has any value been selected when the method is called?
When will the getSelectedValue method return null? Read the API doc for the class and method.
Was This Post Helpful? 2
  • +
  • -

#42 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 11:37 AM

Ok so now i figured out that in order to fix this i had to add a condition if there's no selection.
This fixed the problem.
But now what i don't understand is why in my code i get sometimes no selection when i click enter on a value from the JList
Was This Post Helpful? 0
  • +
  • -

#43 Piet Souris  Icon User is offline

  • D.I.C Head

Reputation: 42
  • View blog
  • Posts: 164
  • Joined: 01-December 15

Re: Joption acting like it's in a for loop

Posted 29 January 2018 - 03:08 PM

Realize that you are adding KeyListener after KeyListener to the JList, that all get called. Together with the 'cntr2++' makes it for me impossible to follow what is going on there. Since these KeyListeners are anonymous, it is not easy to remove one after it has been used.

Can you explain in simple words what it is that you are trying to achieve with this code?
Was This Post Helpful? 1
  • +
  • -

#44 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 30 January 2018 - 09:19 AM

Sure thing what i'm trying to do is search for a word in the search box,on enter move to the JList surf the Jlist using arrows and on enter show a dialog box withthe selected value from the JList then get back to the search box to be able to make this as many times as i wish.
Hope this was clear.
Was This Post Helpful? 0
  • +
  • -

#45 ViSion91  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 112
  • Joined: 26-March 17

Re: Joption acting like it's in a for loop

Posted 30 January 2018 - 11:06 AM

View PostPiet Souris, on 29 January 2018 - 03:08 PM, said:

Realize that you are adding KeyListener after KeyListener to the JList, that all get called. Together with the 'cntr2++' makes it for me impossible to follow what is going on there. Since these KeyListeners are anonymous, it is not easy to remove one after it has been used.

Can you explain in simple words what it is that you are trying to achieve with this code?



Your reply was very helpful i knew whats wrong and managed to solve it.I have 1 more question why when i click enter in the JOptionPane it acts like i entered enter in the search TextField and i need to remove it by using that counter in the listner on the textfield ?

here's my code so far :
package key;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.*;

/**
 *
 * @author ViSion
 */
public class Key {

    public static class SearchContactGui {

        JFrame searchContactFrame;
        JPanel pnl_top, pnl_topLeft, pnl_topCenter, pnl_left, pnl_search;
        JList l_names;
        JScrollPane scrollPane;
        JLabel lbl_searchContact, lbl_search;
        JTextField tf_search;
        ArrayList<String> matchedNames, matchedNumber, contactsNames;
        KeyListener key, k;
        JOptionPane pane = new JOptionPane();
        int cntr = 1;

        SearchContactGui() {

            searchContactFrame = new JFrame("number book");
            pnl_top = new JPanel();

            lbl_searchContact = new JLabel("Search for Contact");
            lbl_searchContact.setFont(new Font("Arial", Font.BOLD, 25));
            lbl_searchContact.setForeground(Color.blue);
            pnl_top.add(lbl_searchContact, BorderLayout.NORTH);

            pnl_left = new JPanel();
            pnl_left.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            pnl_search = new JPanel();
            lbl_search = new JLabel("Search");
            tf_search = new JTextField(18);
            pnl_search.add(lbl_search);
            pnl_search.add(tf_search);
            pnl_left.add(pnl_search, c);
            c.anchor = GridBagConstraints.EAST;
            c.gridx = 0;
            c.gridy = 1;
            c.insets = new Insets(20, 0, 0, 9);

            contactsNames = new ArrayList<String>();
            contactsNames.add("bernard");
            contactsNames.add("beca");
            contactsNames.add("bernard");
            contactsNames.add("brandon");
            contactsNames.add("ben");
            DefaultListModel listModel = new DefaultListModel();

            Collections.sort(contactsNames);
            for (int i = 0; i < contactsNames.size(); i++) {
                listModel.add(i, contactsNames.get(i));
            }

            l_names = new JList();

            l_names.setModel(listModel);

            scrollPane = new JScrollPane();
            scrollPane.setViewportView(l_names);
            scrollPane.setPreferredSize(new Dimension(200, 150));
            pnl_left.add(scrollPane, c);

            searchContactFrame.add(pnl_top, BorderLayout.NORTH);
            searchContactFrame.add(pnl_left, BorderLayout.WEST);
            searchContactFrame.pack();
            searchContactFrame.setVisible(true);
            searchContactFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            tf_search.addKeyListener(key = new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {

                }

                @Override
                public void keyPressed(KeyEvent e) {

                }

                @Override
                public void keyReleased(KeyEvent e) {

                    if (e.getKeyCode() != KeyEvent.VK_ENTER) {
                        listModel.removeAllElements();
                        matchedNumber = new <String>ArrayList();
                        matchedNames = new <String>ArrayList();

                        for (int j = 0; j < contactsNames.size(); j++) {
                            if (contactsNames.get(j).length() >= tf_search.getText().length()) {

                                if (contactsNames.get(j).substring(0, tf_search.getText().length()).equals(tf_search.getText())) {
                                    matchedNames.add(contactsNames.get(j));

                                }
                            }
                        }
                        for (int z = 0; z < matchedNames.size(); z++) {
                            listModel.add(z, matchedNames.get(z));
                        }
                        Collections.sort(matchedNames);

                        l_names.setModel(listModel);
                        scrollPane.setViewportView(l_names);

                    } else {
                        if (cntr++ % 2 == 0) {
                            return;
                        }
                        l_names.requestFocusInWindow();
                        l_names.setSelectedIndex(0);

                    }

                }

            });

            l_names.addKeyListener(k = new KeyListener() {
                @Override
                public void keyTyped(KeyEvent e) {

                }

                @Override
                public void keyPressed(KeyEvent e) {

                }

                @Override
                public void keyReleased(KeyEvent e) {

                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {

                        JOptionPane pane = new JOptionPane();
                        if (l_names.isSelectionEmpty()) {
                            System.out.println("is empty");
                        } else {
                            System.out.println(l_names.getSelectedValue().toString());

                            int input = pane.showOptionDialog(searchContactFrame, l_names.getSelectedValue().toString(), "title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                            pane.requestFocusInWindow();
                            if (input == JOptionPane.OK_OPTION) {

                                System.out.println("ok");
                                l_names.clearSelection();
                                tf_search.requestFocus();

                            }
                        }

                    }
                }
            });

        }

    }

    public static void main(String[] args) {
        new SearchContactGui();
    }

}


Was This Post Helpful? 0
  • +
  • -

  • (4 Pages)
  • +
  • 1
  • 2
  • 3
  • 4