Adding a MouseListener to a panel

前端 未结 5 1699
轻奢々
轻奢々 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:33

    I'm not super familiar with Swing. As a new programmer, I've only worked with JavaFX.

    However you have no reference to the MouseListener anywhere in your program. You probably forget to instantiate it.

    0 讨论(0)
  • 2021-01-29 07:35

    You have to register the listener object with the Jpanel using the addMouseListener method. More info;

    • https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html

    • https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-29 07:52

    cam, given what you're doing, I hopped on my "work machine" and grabbed this code. It draws a rectangle on top of an image, and the rectangle only shows up after you release the mouse (it's a work in progress, unpaid, done in my spare time for stuff my employer might like). But since you're looking ahead to drawing, etc., here it is.

    Uses a JDialog because I wanted it to be modal; don't let that bother you.

    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    
    import javax.swing.GroupLayout;
    import javax.swing.JDialog;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.WindowConstants;
    
    public class RectSelectGUI extends JDialog implements MouseListener, ActionListener, WindowListener {
                    private static final long serialVersionUID = 1L;
                    public int overheadWd;
                    public int overheadHt;
                    public ImageJPanel imagePanel;
                    private JMenu jMenuSelection;
                    private JMenuBar jMenuBar1;
                    private Dimension mouseDownLoc;
                    private String errorString;
    
                    public RectSelectGUI(String imgFileName) {
                                    initComponents(imgFileName);
                    }
    
                    private void initComponents(String imgFileName) {
    
                                    imagePanel = new ImageJPanel(imgFileName);
                                    jMenuBar1 = new JMenuBar();
                                    jMenuSelection = new JMenu();
            JMenuItem jMenuItemSave = new JMenuItem();
            jMenuItemSave.setActionCommand("Save");
            jMenuItemSave.addActionListener(this);
            jMenuItemSave.setText("Save");
            jMenuSelection.add(jMenuItemSave);
            JMenuItem jMenuItemCancel = new JMenuItem();
            jMenuItemCancel.setActionCommand("Cancel");
            jMenuItemCancel.addActionListener(this);
            jMenuItemCancel.setText("Cancel");
            jMenuSelection.add(jMenuItemCancel);
    
                                    mouseDownLoc = new Dimension();
                                    errorString = "No selection";
    
                                    imagePanel.addMouseListener(this);
    
                                    this.setModal(true);
                                    this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
                                    this.addWindowListener(this);
    
                                    GroupLayout jPanel1Layout = new GroupLayout(imagePanel);
                                    imagePanel.setLayout(jPanel1Layout);
                                    jPanel1Layout.setHorizontalGroup(
                                                                    jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 524, Short.MAX_VALUE));
                                    jPanel1Layout.setVerticalGroup(
                                                                    jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 370, Short.MAX_VALUE));
    
                                    jMenuSelection.setText("Selection");
                                    jMenuBar1.add(jMenuSelection);
    
                                    setJMenuBar(jMenuBar1);
    
                                    GroupLayout layout = new GroupLayout(getContentPane());
                                    getContentPane().setLayout(layout);
                                    layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                                    .addGroup(layout.createSequentialGroup().addContainerGap()
                                                                                                    .addComponent(imagePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                                                    .addContainerGap()));
                                    layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                                    .addGroup(layout.createSequentialGroup().addContainerGap()
                                                                                                    .addComponent(imagePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                                                    .addContainerGap()));
    
                                    pack();
    
                                    overheadWd = this.getWidth() - imagePanel.getWidth();
                                    overheadHt = this.getHeight() - imagePanel.getHeight();
    
                    }
    
                    public String getSelectionString() {
                                    if (errorString.isEmpty()) {
                                                    double rectWd = (double) imagePanel.rectWd;
                                                    double rectHt = (double) imagePanel.rectHt;
                                                    double rectX = (double) imagePanel.rectX;
                                                    double rectY = (double) imagePanel.rectY;
                                                    if (Math.abs(RectSelect.displayFactor - 1.0) > 0.001) {
                                                                    System.out.println("Adjusting by displayFactor (" + RectSelect.displayFactor + ")");
                                                                    rectWd /= RectSelect.displayFactor;
                                                                    rectHt /= RectSelect.displayFactor;
                                                                    rectX /= RectSelect.displayFactor;
                                                                    rectY /= RectSelect.displayFactor;
                                                    }
                                                    return Math.round(rectWd) + "x" + Math.round(rectHt) + "+" + Math.round(rectX) + "+" + Math.round(rectY);
                                    } else {
                                                    return "ERROR: " + errorString;
                                    }
                    }
    
    
                    @Override
                    public void mouseClicked(MouseEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void mousePressed(MouseEvent evt) {
                                    mouseDownLoc.setSize(evt.getX(), evt.getY());
                    }
    
                    @Override
                    public void mouseReleased(MouseEvent evt) {
                                    Dimension mouseUpLoc = new Dimension(evt.getX(), evt.getY());
                                    if (mouseDownLoc.width < mouseUpLoc.width) {
                                                    imagePanel.rectX = mouseDownLoc.width;
                                                    imagePanel.rectWd = mouseUpLoc.width - mouseDownLoc.width;
                                    } else {
                                                    imagePanel.rectX = mouseUpLoc.width;
                                                    imagePanel.rectWd = mouseDownLoc.width - mouseUpLoc.width;
                                    }
                                    if (mouseDownLoc.height < mouseUpLoc.height) {
                                                    imagePanel.rectY = mouseDownLoc.height;
                                                    imagePanel.rectHt = mouseUpLoc.height - mouseDownLoc.height;
                                    } else {
                                                    imagePanel.rectY = mouseUpLoc.height;
                                                    imagePanel.rectHt = mouseDownLoc.height - mouseUpLoc.height;
                                    }
                                    imagePanel.haveNewRect = true;
                                    imagePanel.repaint();
                                    errorString = "";
                    }
    
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                                    String cmd = evt.getActionCommand();
                                    switch (cmd) {
                                    case "Save":
                                                    break;
                                    case "Cancel":
                                                    errorString = "Cancelled";
                                                    break;
                                    default:
                                                    System.out.println("Unknown action command " + cmd);
                                    }
                                    this.setVisible(false);
                    }
    
                    @Override
                    public void windowClosing(WindowEvent e) {
                                    errorString = "Cancelled";
                                    this.setVisible(false);
                    }
    
                    @Override
                    public void mouseEntered(MouseEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void mouseExited(MouseEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void windowOpened(WindowEvent e) {
                                    try {
                                                    Thread.sleep(100);
                                    } catch (InterruptedException e1) {
                                    }
                                    this.repaint();
                    }
    
                    @Override
                    public void windowClosed(WindowEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void windowIconified(WindowEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void windowDeiconified(WindowEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
                    @Override
                    public void windowActivated(WindowEvent e) {
                    }
    
                    @Override
                    public void windowDeactivated(WindowEvent e) {
                                    // TODO Auto-generated method stub
    
                    }
    
    }
    
    
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    
    public class ImageJPanel extends JPanel {
                    private static final long serialVersionUID = 1L;
                    public Image localImage;
                    private int origWd;
                    private int origHt;
                    private int displayWd;
                    private int displayHt;
                    public int rectX;
                    public int rectY;
                    public int rectWd;
                    public int rectHt;
                    public boolean haveNewRect;
                    private Toolkit toolkit;
    
                    ImageJPanel(String imageFileName) {
                                    toolkit = Toolkit.getDefaultToolkit();
                                    localImage = toolkit.getImage(imageFileName);
                    }
    
                    protected void paintComponent(Graphics g1D) {
                                    Graphics2D g;
                                    g = (Graphics2D) g1D;
                                    // Draw the image using the Graphics object provided
                                    g.drawImage(localImage, 0, 0, getDisplayWd(), getDisplayHt(), null);
                                    /*
                                    * Optional label.
                                    Font font = new Font("SansSerif", Font.BOLD, 24);
                                    g1D.setFont(font);
                                    FontMetrics metrics = g1D.getFontMetrics();
                                    int ht = metrics.getHeight();
                                    int wd = metrics.stringWidth(this.imageFileName);
                                    g.setColor(Color.LIGHT_GRAY);
                                    g.fillRect(this.getWidth() - wd - 10, this.getHeight() - ht, wd + 10, ht);
                                    g1D.setColor(new Color(55, 11, 160));
                                    g1D.drawString(this.imageFileName, this.getWidth() - wd - 10, this.getHeight() - ht + 20);
                        */
    
                                    // Draw a selection rectangle if requested.
                                    if (haveNewRect) {
                                                    g.drawRect(rectX, rectY, rectWd, rectHt);
                                                    haveNewRect = false;
                                    }
                    }
    
                    public int getDisplayWd() {
                                    return displayWd;
                    }
    
                    public void setDisplayWd(int displayWd) {
                                    this.displayWd = displayWd;
                    }
    
                    public int getDisplayHt() {
                                    return displayHt;
                    }
    
                    public void setDisplayHt(int displayHt) {
                                    this.displayHt = displayHt;
                    }
    
                    public int getOrigWd() {
                                    return origWd;
                    }
    
                    public void setOrigWd(int origWd) {
                                    this.origWd = origWd;
                    }
    
                    public int getOrigHt() {
                                    return origHt;
                    }
    
                    public void setOrigHt(int origHt) {
                                    this.origHt = origHt;
                    }
    
    }
    
    0 讨论(0)
  • 2021-01-29 07:55

    I would strongly recommend you start by having a read through How to Write a Mouse Listener. When ever you get stuck, these tutorials (and the JavaDocs) are the best place to get started

    The "immediate" answer to your question is, you need to register an instance of the MouseListener with your component, maybe something like...

    private JPanel createCenterPanel() {
    
        panel.addMouseListener(new MouseListen());
        //panel.setLayout(null);
    
    
        return panel;
    }
    

    This will "answer" your immediate issue.

    However, you'll find it hard to try and marry up the actions of the MouseListener with the panel, which needs to paint the results.

    A better solution might be to start with a JPanel which manages it's own MouseListener

    Also, Graphics g = panel.getGraphics() isn't how custom painting should be performed. Take a look at Performing custom painting for more details

    So, instead, it might look something more like...

    public class TrianglePanel extends JPanel {
    
        private List<Point> points = new ArrayList<>(3);
    
        public TrianglePanel() {
            addMouseListener(new MouseListen());
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
    
            if (points.size() < 1) {
                return;
            }
            for (int index = 0; index < points.size(); index++) {
                Point nextPoint = points.get(index);
                g.fillOval(nextPoint.x - 2, nextPoint.y - 2, 4, 4);
            }
    
            Point startPoint = points.get(0);
            Point lastPoint = startPoint;
            for (int index = 1; index < points.size(); index++) {
                Point nextPoint = points.get(index);
                g.drawLine(lastPoint.x, lastPoint.y, nextPoint.x, nextPoint.y);
                lastPoint = nextPoint;
            }
            g.drawLine(lastPoint.x, lastPoint.y, startPoint.x, startPoint.y);
        }
    
        class MouseListen extends MouseAdapter {
    
            public void mouseReleased(MouseEvent e) {
                if (points.size() < 3) {
                    points.add(e.getPoint());
                    repaint();
                }
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题