Adding a MouseListener to a panel

前端 未结 5 1693
轻奢々
轻奢々 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: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;
                    }
    
    }
    

提交回复
热议问题