将MouseListener添加到面板

时间:2018-04-30 01:19:04

标签: java swing jpanel mouselistener

我正在尝试将鼠标操作添加到我的面板中。 这就是该计划应该做的事情:

  

编写一个程序,允许用户通过三次鼠标按下指定三角形。第一次鼠标按下后,画一个小点。第二次鼠标按下后,绘制一条连接前两点的线。第三次鼠标按下后,绘制整个三角形。第四次鼠标按下删除旧三角形并开始一个新三角形。

5 个答案:

答案 0 :(得分:2)

我强烈建议您先阅读How to Write a Mouse Listener。当你遇到困难时,这些教程(以及JavaDocs)是开始的最佳场所

您的问题的“直接”答案是,您需要在您的组件中注册MouseListener的实例,可能类似......

private JPanel createCenterPanel() {

    panel.addMouseListener(new MouseListen());
    //panel.setLayout(null);


    return panel;
}

这将“回答”您当前的问题。

但是,您会发现很难尝试将MouseListener的操作与面板结合起来,而面板需要绘制结果。

更好的解决方案可能是从JPanel开始管理它自己的MouseListener

此外,Graphics g = panel.getGraphics()不是应该如何执行自定义绘画。看看Performing custom painting for more details

所以,相反,它可能看起来更像......

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();
            }
        }
    }

}

答案 1 :(得分:1)

我没有看到你实例化类MouseListen的任何地方。您还需要调用addMouseListener()。

以下是我前一段时间写过的内容中的行:

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()));
    }
}

请参阅https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html上的教程。

此外,基于https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html,您可以让您的JFrame实现MouseListener,这将使您的代码更简单。 (你根本不需要类MouseListen。)

通过过去的Java代码快速写一下我写的确认你可以

public class MyFrame extends JFrame implements MouseListener

所以你可能想看看这个。

答案 2 :(得分:0)

我对Swing并不是很熟悉。作为一名新程序员,我只使用过JavaFX。

但是,您在程序的任何位置都没有引用MouseListener。你可能忘了实例化它。

答案 3 :(得分:0)

答案 4 :(得分:0)

鉴于你正在做的事情,我跳上了我的“工作机器”并抓住了这段代码。它在图像顶部绘制一个矩形,并且只有在你释放鼠标后才显示矩形(这是一项正在进行的工作,未支付,在我的业余时间为我的雇主所喜欢的东西完成)。但是既然你正在展望绘画等等,这就是它。

使用JDialog,因为我希望它是模态的;不要那么打扰你。

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;
                }

}
相关问题