Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

java - How to add MouseListener to actionPerformed?

I don't know how I can add mouseListener (mouseClicked, mouseEntered, etc...) to my actionPerformed. I learned only how to add action from JButton but mouseListener is in JLabel.

Here it's this code:

test = new JLabel (ikona);
    test.setBounds(200, 200, 100, 100);
    add(test);
    test.addMouseListener(new MouseListener()
    {

        public void mouseClicked(MouseEvent e) {
            System.out.println(ikona2);

        }

        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

and:

public void actionPerformed(ActionEvent arg0) 
{
    Object Zrodlo = arg0.getSource();
    if (?ród?o==przycisk)
    {
    wyswietlacz.setText(new Date().toString());
    //System.out.println(new Date());
    }
    else if (Zrodlo==przycisk2)
    {
        dispose();
    }
    else if (Zrodlo==przycisk3)
    {
    wyswietlacz.setText(new Date().toString());
    }
    else if (Zrodlo==test)
    {
        wyswietlacz.setText("");
    }

"przycsik, przycisk2, przycisk3" are JButton, I try doing something with JLAbel ("test") but I don't have idea how solve this.

P.S. sorry for my english...

EDIT: For JButton I use this to see action in mine JFrame:

public void actionPerformed(ActionEvent arg0) 
{
    Object Zrodlo = arg0.getSource();
    if (?ród?o==przycisk)
    {
    wyswietlacz.setText(new Date().toString());
    //System.out.println(new Date());
    }
    else if (?ród?o==przycisk2)
    {
        dispose();
    }

I want to do same with my JLabel and mouseListener. I want see interaction which mouse/cursor which MouseListener. I want to add icon(gif) to JLabel and use MouseListener to change icon1 to icon2 example mouseClicked or mousePressed. If I use:

test.addMouseListener(new MouseListener()
    {

        public void mouseClicked(MouseEvent e) {
            System.out.println(ikona2);

        }

I only see source to my "ikona2" in my Eclipse Console. I want to see action in my JFrame.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not sure I understand the question but you can paint a JButton like a JLabel but still have the ActionListener work like a button:

JButton button3 = new JButton("Label Button");
button3.setBorderPainted(false);
button3.setContentAreaFilled(false);
button3.addActionListener( ... );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...