-1

I've got a problem, and I can't find an answer by myself. I'm making a simple chat in java, and I populated a JList with names. When a name is double-clicked, that name needs to be passed as an argument to another frame (as a recipient name). But, double click does not work

I've got a main class InstantMessageFrame, in which a JList named friends is initialized and filled with an array of strings.

private JList<String> friends;
String names[] = { "Ana", "Banana", "Cikla", "Doris", "Ema", "Mirna","Matea","Veronika","Vera","Marta","Mirta","Davor","Marko","Matko","Kloki" };
JList<String> friends = new JList<String>(names);

Also,I added a listener to my JList

DisplayMessageDialog dmd = new DisplayMessageDialog();
friends.addMouseListener(dmd);

This is my DisplayMessageDialog class which checks if there was a double click. If there is a double click, a new Frame should appear. None of the lines in the first "if" statement executes (one with the e.getClickCount())

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisplayMessageDialog extends MouseAdapter
{
    public void mouseClicked(MouseEvent e)
    {
        JList theList = (JList) e.getSource();
        if (e.getClickCount() == 2) 
        {
            int index = theList.locationToIndex(e.getPoint());
            if (index >= 0) 
            {
                Object o = theList.getModel().getElementAt(index);
                InstantMessageDialog imd = new InstantMessageDialog(null, o.toString());
                imd.setVisible(true);
            System.out.println("Double-clicked on: " + o.toString());
            }
        }
    }
}

This is how it should look like:

https://i.stack.imgur.com/Bex5U.png

And when double clicked,a new frame should appear (in code "InstantMessageDialog" object)

https://i.stack.imgur.com/yjvW6.png

And it should look like this.

spamserv
  • 165
  • 3
  • 15
  • 1
    `"But, double click does not work..."` -- please elaborate as "does not work" by itself is very frustrating to us since it tells us nothing of use. What exactly do you mean by this? How does it not work? What problems are you encountering? What have your attempts to debug this revealed? Also consider posting a [mcve]. – Hovercraft Full Of Eels Sep 14 '15 at 21:49
  • What I meant by it does not work is - when I double click on a name from a JList,nothing is changed,nothing has been done,like I didn't add a listener to the JList – spamserv Sep 14 '15 at 21:51
  • 2
    Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Sep 14 '15 at 21:52
  • I think that you'll need to create and post your [mcve] for us to guess what is not working. Please click on the link. – Hovercraft Full Of Eels Sep 14 '15 at 21:52
  • I edited the questions and gave some more informations. I hope you know what bothers me know. Thank you :) – spamserv Sep 14 '15 at 22:09
  • 2
    Please re-read the [mcve] link that have been given now 4 times by two different Swing experts. If anything in the link confuses you, please ask for clarification. – Hovercraft Full Of Eels Sep 14 '15 at 22:18
  • *"I've got a problem,"* ..do you have a question, and if so, what is it? *"If there is a double click, a new Frame should appear."* See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Sep 14 '15 at 23:09
  • I put your code into a JFrame and replaced the reference to InstantMessageDialog with a simple call to JOptionPane.showMessage() to test it, and it worked fine. Looks to me like the problem might lie within the InstantMessageDialog code, which you haven't supplied. In the absence of the [MCVE](http://stackoverflow.com/help/mcve) code which other experts have requested, there is little more that anyone here can do for you, sorry! – Julian Wright Sep 14 '15 at 23:16

2 Answers2

3

So working off your out-of-context code snippets, this example seems to work just fine, so I can only surmise that your problem is else where in your code that you're not showing us...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JList<String> friends;

        public TestPane() {
            String names[] = {"Ana", "Banana", "Cikla", "Doris", "Ema", "Mirna", "Matea", "Veronika", "Vera", "Marta", "Mirta", "Davor", "Marko", "Matko", "Kloki"};
            JList<String> friends = new JList<String>(names);

            setLayout(new BorderLayout());
            add(new JScrollPane(friends));

            DisplayMessageDialog dmd = new DisplayMessageDialog();
            friends.addMouseListener(dmd);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }

    }

    public class DisplayMessageDialog extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            JList theList = (JList) e.getSource();
            //              if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
            if (e.getClickCount() == 2) {
                int index = theList.locationToIndex(e.getPoint());
                if (index >= 0) {
                    Object o = theList.getModel().getElementAt(index);
                            //InstantMessageDialog imd = new InstantMessageDialog(null, o.toString());
                    //imd.setVisible(true);
                    JOptionPane.showMessageDialog(theList, "Double-clicked on: " + o.toString());
                    System.out.println("Double-clicked on: " + o.toString());
                }
            }
        }
    }
}

I might add though, you "double click" check probably should be something more like...

if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {

Assuming your really only want to respond to left mouse clicks

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I tested the program and changed some of my code,to your code,and realised the problem was in my getFriendsPane,in which I added JList friends to JScrollPane so I deleted my method and replaced it with add(new JScrollPane(friends)); – spamserv Sep 15 '15 at 10:02
3

When a name is double-clicked...

When designing a GUI it is always a good idea to provide support for the mouse and keyboard.

Check out List Action. It adds Action support to a JList. All you need to do is provide the Action. Then the Action can be invoked by:

  1. double clicking, or
  2. using the Enter key.

The most basic example of using the ListAction would be:

String[] data = { "zero", "one", "two", "three", "four", "five" };
JList list = new JList( data );

Action displayAction = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        JList list = (JList)e.getSource();
        System.out.println(list.getSelectedValue());
    }
};

ListAction la = new ListAction(list, displayAction);
camickr
  • 321,443
  • 19
  • 166
  • 288