Adding a MouseListener to a panel

前端 未结 5 1700
轻奢々
轻奢々 2021-01-29 07:10

I am trying to add the mouse actions to my panel. This is what the program is supposed to do:

Write a program that allows the user to specify a triangle

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 07:49

    I don't see anywhere you instantiate class MouseListen. Also you need to call addMouseListener().

    Here are lines from something I wrote a while back that worked:

    public class ColorPanel extends JPanel implements MouseListener {
    
       . . .
    
    ColorPanel(JTextField jTextFieldColor) {
        super();
        this.jTextField = jTextFieldColor;
        addMouseListener(this);
    }
    
    @Override
    public void mouseClicked(MouseEvent evt) {
        System.out.println("Instance of ColorPanel clicked.");
        jColorChooser = new JColorChooser(this.getBackground());
        this.add(jColorChooser);
        int retval = JOptionPane.showConfirmDialog(null,
                jColorChooser,
                "JOptionPane Example : ",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE);
        if (retval == JOptionPane.OK_OPTION) {
            jTextField.setText(Utils.hexStringFromColor(jColorChooser.getColor()));
        }
    }
    

    See the tutorial at https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html.

    Also, based on https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html, you might be able to have your JFrame implement the MouseListener, which would make your code even simpler. (You wouldn't need class MouseListen at all.)

    A quick grep though past Java code I've written confirms you could

    public class MyFrame extends JFrame implements MouseListener
    

    so you might want to look into this.

提交回复
热议问题