如何在自定义的JComponent中正确实现MouseInputListener

huangapple go评论96阅读模式
英文:

How to properly implement MouseInputListener in custom JComponent

问题

我正在尝试向我构建的自定义组件实现一些MouseListener功能然而在使其正常工作方面我遇到了一些障碍这里是自定义JComponent的代码

```java
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputListener;

public class PhotoComponent extends JComponent implements MouseInputListener {
    
    private ImageIcon pic;
    Boolean flipped = false;

    public PhotoComponent() {

    }

    public PhotoComponent(ImageIcon p) {
        pic = p;
    }

    @Override
    public Dimension getPreferredSize() {
        if (pic == null) {
            return new Dimension(0, 0);
        }
        return new Dimension(pic.getIconWidth(), pic.getIconHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        if (!flipped) {
            pic.paintIcon(this, g, 0, 0);
        }

        if (flipped) {
            g.setColor(Color.WHITE);
            g.drawRect(0, 0, pic.getIconWidth(), pic.getIconHeight());
            g.fillRect(0, 0, pic.getIconWidth(), pic.getIconHeight());
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            flipped = !flipped;
            repaint();
            jl.settext("hi"); // 这里有一个错误,应该是 jl.setText("hi");
        }
    }

    // 其他MouseListener方法的实现...
}

目标是通过双击鼠标在真实图像和全白版本之间进行切换。这个组件将在下面的代码中被使用。

public class Base extends JFrame {
    // ...

    public Base() {
        // ...

        picList = new ArrayList<PhotoComponent>(5);
        pos = 0;
        mainScroll = new JScrollPane();

        // ...

        impo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent fo) {
                // ...

                if (response == JFileChooser.APPROVE_OPTION) {
                    File[] chosen = chooser.getSelectedFiles();
                    for (File f : chosen) {
                        if (f.isDirectory()) {
                            File[] temp = f.listFiles();
                            for (File x : temp) {
                                ImageIcon ii = new ImageIcon(x.getAbsolutePath());
                                picList.add(new PhotoComponent(ii));
                            }
                        } else {
                            ImageIcon ii = new ImageIcon(f.getAbsolutePath());
                            picList.add(new PhotoComponent(ii));
                        }
                    }
                    mainScroll.setViewportView(picList.get(pos));

                    // 添加MouseListener到组件
                    picList.get(pos).addMouseListener(picList.get(pos));
                    mainScroll.setVisible(true);

                    validate();
                } else {
                    JOptionPane.showMessageDialog(null, "Oops, something's wrong");
                }
            }
        });

        // ...
    }
}

迄今为止,我在尝试时并没有从鼠标监听器中得到任何响应。我做错了什么,我该如何更好地实现这个?我尝试将addMouseListener(this)添加到组件中,但它一直给我语法错误,并告诉我它“需要一个主体”。我的代码错误一直建议我添加:

@Override
public synchronized void addMouseListener(MouseListener l) {
    // TODO Auto-generated method stub
    super.addMouseListener(l);
}

但我不太确定该怎么做。


<details>
<summary>英文:</summary>
I&#39;m trying to implement some mouseListener functionality to a custom component I built. However, I&#39;m running into some roadblocks getting it to work. Here is the code for the custom JComponent.

import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputListener;

import org.w3c.dom.events.MouseEvent;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.lang.reflect.Field;
import java.util.prefs.Preferences;

public class PhotoComponent extends JComponent implements MouseInputListener{

private ImageIcon pic;
Boolean flipped = false;
public PhotoComponent(){
}
public PhotoComponent(ImageIcon p){
pic=p;
}
@Override
public Dimension getPreferredSize(){
if(pic==null){
return new Dimension(0,0);
}
return new Dimension(pic.getIconWidth(), pic.getIconHeight());
}
@Override
protected void paintComponent(Graphics g){
if (flipped==false){
pic.paintIcon(this, g, 0, 0);
}
if (flipped==true){
g.setColor(Color.WHITE);
g.drawRect(0, 0, pic.getIconWidth(), pic.getIconHeight());
g.fillRect(0,0, pic.getIconWidth(), pic.getIconHeight());
}
}
@Override
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2){
flipped=!flipped;
repaint();
jl.settext(&quot;hi&quot;);
}
}
@Override
public void mousePressed(MouseEvent e){
//lol
}
@Override
public void mouseReleased(MouseEvent e){
//lol
}
@Override
public void mouseEntered(MouseEvent e){
//lol
}
@Override
public void mouseExited(MouseEvent e){
//lol
}

}

The goal is to switch between the real image and an all-white version of it with a double click of the mouse. The component will be utilized in this code below.

public class Base extends JFrame {
private JPanel radio, buttons, tags, container, statusContainer;
private JScrollPane mainScroll;
private JButton next, prev, delete;
private JMenuBar jmb;
private JMenu file, view;
private JMenuItem impo;
private JLabel jl;
private ArrayList<PhotoComponent> picList;
private int pos;

public static void main(String[] args) {
new Base();
}
public Base(){
setTitle(&quot;Placeholder&quot;);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setResizable(true);
menusAndLabels();
pack();
setVisible(true);
}
public void menusAndLabels(){
jmb = new JMenuBar();
setJMenuBar(jmb);
file=new JMenu(&quot;File&quot;);
statusContainer = new JPanel();
add(statusContainer, BorderLayout.SOUTH);
jmb.add(file);
impo = new JMenuItem(&quot;Import&quot;);
//currentPic= new PhotoComponent();
picList= new ArrayList&lt;PhotoComponent&gt;(5);
pos = 0;
mainScroll = new JScrollPane();
add(mainScroll);
impo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent fo){
JFileChooser chooser= new JFileChooser(&quot;&quot;);
FileFilter filter = new FileNameExtensionFilter(&quot;Graphics&quot;, &quot;jpg&quot;,&quot;jpeg&quot;,&quot;png&quot;);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);
int response = chooser.showOpenDialog(null);
if(response == JFileChooser.APPROVE_OPTION){
File[] chosen = chooser.getSelectedFiles();
for (File f:chosen) {
if(f.isDirectory()){
File[] temp=f.listFiles();
for (File x:temp){;
ImageIcon ii =new ImageIcon(x.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
else{
ImageIcon ii =new ImageIcon(f.getAbsolutePath());
picList.add(new PhotoComponent(ii));
}
}
mainScroll.setViewportView(picList.get(pos));
///mainScroll.addMouseListener(picList.get(pos));
mainScroll.setVisible(true);
validate();
}
else {
JOptionPane.showInputDialog(&quot;oops somethings wrong&quot;);
}
}
});
file.add(impo);
}

}


So far I get no response from my mouse listener when I try. What am I doing wrong, and how might I better implement this?
I tried adding addMouseListener(this) to the component, but it keeps giving me syntax erroes and tells me that it &quot;requires a body&quot;. My code error keeps suggesting I add:

@Override
public synchronized void addMouseListener(MouseListener l) {
// TODO Auto-generated method stub
super.addMouseListener(l);
}

but I&#39;m not entirely sure what to do with that.
</details>
# 答案1
**得分**: 0
&gt; 到目前为止,我没有从我的鼠标监听器那里得到任何响应
您在组件中的哪里添加了MouseListener?
您需要将监听器添加到类中,以便它可以响应事件。在您的构造函数中,您需要像这样的代码:
addMouseListener( this );
阅读Swing教程中关于[如何编写MouseListener](https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html)的部分,其中包含一个可工作的示例。
<details>
<summary>英文:</summary>
&gt; So far I get no response from my mouse listener
Where do you add the MouseListener to the component?
You need to add the listener to the class so it can respond to events. In your constructor you need code like:
addMouseListener( this );
Read the section from the Swing tutorial on [How to Write a MouseListener](https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html) for a working example.
</details>

huangapple
  • 本文由 发表于 2020年9月20日 13:03:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63975673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定