简体   繁体   English

java - 如何在按钮上获得鼠标按下事件

[英]How can I get mouse pressed event in java on a button

I am creating a program in Java, and would like to make my own button class as opposed to using a JButton.我正在用 Java 创建一个程序,并且想制作自己的按钮类而不是使用 JButton。 I've got all the aesthetics sorted out but I'm not sure how to get the mouse pressed event in Java.我已经整理出了所有的美学,但我不确定如何在 Java 中获得鼠标按下事件。 This is my code:这是我的代码:

// Button.java
package cella;

import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;

import java.awt.event.MouseEvent;

public class Button extends MouseAdapter {
    int x, y, w, h;
    String ph, val;
    boolean mouseDown;
    Color LIGHTGRAY = new Color(200, 200, 200);
    public Button(int xt, int yt, int wt, int ht, String pht, String valt) {
        x = xt;
        y = yt;
        w = wt;
        h = ht;
        ph = pht;
        val = valt;
        mouseDown = false;
    }

    public void draw(Graphics g, Point mouse) {
        if (contains(mouse)) {
            g.setColor(Color.GRAY);
        } else {
            g.setColor(LIGHTGRAY);
        }
        g.fillRect(x, y, w, h);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, w, h);
        g.drawString(ph, x + 5, y + h - 5);
    }   

    private boolean contains(Point pos) {
        if (pos.x > x && pos.x < x + w && pos.y > y && pos.y < y + h) {
            return true;
        } else {
            return false;
        }
    }
    public boolean pressed(Point pos) {
        if (contains(pos) && mouseDown) {
            System.out.println("Pressed");
            return true; 
        }
        else return false;
    }
}

The boolean mouseDown will be set to true when the mouse is pressed and then false when released however i can't find a way to catch these events, mouseListener gives errors about needing abstract classes when i try to implement it.按下鼠标时布尔mouseDown将设置为true ,然后释放时设置为false但是我找不到捕获这些事件的方法,当我尝试实现它时mouseListener会给出有关需要抽象类的错误。 Thanks for any help you can give me.感谢你给与我的帮助。

Full code完整代码

Try this.尝试这个。

JButton button = new JButton("Click!");

button.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent e) {
    if (e.getButton() == MouseEvent.NOBUTTON) {
      textArea.setText("No button clicked...");
    } else if (e.getButton() == MouseEvent.BUTTON1) {
      textArea.setText("Button 1 clicked...");
    } 

  }
});

See available methods查看可用方法

Hope this help!希望这有帮助!

You can add a listener to your button that handles the event.您可以将侦听器添加到处理事件的按钮。

JButton button = new JButton("Click for Stuff");

button.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent e) {
    switch(e.getButton())
     { 
      case MouseEvent.NOBUTTON : // do stuff on button release
           break;
      case MouseEvent.BUTTON1 : // do stuff on click
           break;

     }
  }
});

I know this question is a few years old, but I thought my input might be useful to someone down the road trying to accomplish the same task, considering I have some experience in custom UIs.我知道这个问题已经有几年的历史了,但考虑到我在自定义 UI 方面有一些经验,我认为我的输入可能对尝试完成相同任务的人有用。

If you want a fully non-JComponent button, then you're going to need to also program your mouselistener and a UI Object Registry and a render/update function all operating on their required threads.如果您想要一个完全非 JComponent 的按钮,那么您还需要对鼠标侦听器和 UI 对象注册表和渲染/更新函数进行编程,所有这些都在它们所需的线程上运行。 I've done that, complete with NumberInputFields, Buttons, PasswordFields, TextFields, TextAreas, Graphics, and a variety of other UI objects.我已经完成了,包括 NumberInputFields、Buttons、PasswordFields、TextFields、TextAreas、Graphics 和各种其他 UI 对象。 You don't want to unless you're going for a radically different look and feel than what is already supplied with very different functionality (for instance, my TextArea and TextField took in BitLines made up of TextBits rather than Strings, which allowed for each character to individually be formatted or colored or sized, complete with customized hover and click events).你不想这样做,除非你想要一个完全不同的外观和感觉,而不是已经提供了非常不同的功能(例如,我的 TextArea 和 TextField 采用由 TextBits 而不是 Strings 组成的 BitLines,这允许每个字符可以单独设置格式、颜色或大小,并带有自定义的悬停和单击事件)。 If such a different result is desired, you would do well to look into everything that goes into making a full UI within a Canvas object.如果需要这种不同的结果,您最好查看在 Canvas 对象中制作完整 UI 的所有内容。 If not, you have a couple other options.如果没有,您还有其他几个选择。

Option 1: Extend the JButton class like has already been suggested.选项 1:像已经建议的那样扩展 JButton 类。 This is the easiest and likely the best option for you.这是最简单的,可能是您的最佳选择。 It's fairly simple, and you can make that button be whatever you want it to be (within reason, of course).这相当简单,您可以使该按钮成为您想要的任何东西(当然,在合理范围内)。

Option 2: Create your own custom look and feel by extending the BasicLookAndFeel class.选项 2:通过扩展 BasicLookAndFeel 类创建您自己的自定义外观。 This is more complex and may take a bit of time and research, but in the end you can format all of your program to have a consistent L&F throughout, giving a satisfying and unique look to your software.这更复杂,可能需要一些时间和研究,但最终您可以格式化所有程序以使 L&F 始终保持一致,从而为您的软件提供令人满意且独特的外观。

Here's an example of what it can take to make a button with basic functionality, completely separate from the JComponent class.下面是一个示例,说明如何制作具有基本功能的按钮,完全独立于 JComponent 类。 Please note that this does NOT include the many background classes required to make this operate, such as the registry, the renderer, the animation and image loaders, the listeners, etc.请注意,这不包括进行此操作所需的许多背景类,例如注册表、渲染器、动画和图像加载器、侦听器等。

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

import dev.blue.neuron.storage.Animation;

public class Button extends UIObject {
    private Animation whileDown;

    private Animation whileUp;

    private int tooltipTimer = 0;

    private boolean showTooltip = false;

    private boolean useTooltip = false;

    protected boolean showingClicked = false;

    protected boolean isSelected;

    private boolean showID;

    private int fontSize;

    private Color color = Color.BLACK;

    public Button(String id, boolean showID, boolean useTooltip, int fontSize, int x, int y, int width, int height,
            int animationSpeed, Animation whileDown, Animation whileUp) {
        this.id = id;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.whileDown = whileDown;
        this.whileUp = whileUp;
        this.bounds = new Rectangle(x, y, width, height);
        this.showID = showID;
        this.fontSize = fontSize;
        this.useTooltip = useTooltip;
    }

    public void render(Graphics g) {
        animate();
        this.whileUp.render(g);
        this.whileDown.render(g);
        if (this.showID) {
            g.setFont(new Font("Helvetica", 1, this.fontSize));
            g.setColor(this.color);
            g.drawString(this.id, this.x + this.width / 2 - g.getFontMetrics().stringWidth(this.id) / 2,
                    (int) ((this.y + this.height / 2) + g.getFontMetrics().getHeight() / 3.5D));
        }
        if (this.showTooltip && this.useTooltip) {
            g.setFont(new Font("Helvetica", 0, 12));
            g.setColor(Color.GRAY);
            g.drawString(this.id, this.x, (int) (this.y + g.getFontMetrics().getHeight() * 1.5D));
        }
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public void update() {
        if (this.hovering) {
            this.tooltipTimer++;
        } else if (this.showingClicked) {
            this.showingClicked = false;
        }
        if (this.tooltipTimer >= 50)
            this.showTooltip = true;
        runOnUpdate();
    }

    public void runOnUpdate() {
    }

    public void onMouseMove(Point p) {
        if (this.bounds.contains(p)) {
            if (!this.hovering) {
                this.hovering = true;
                runOnHover();
            }
        } else if (this.hovering) {
            this.hovering = false;
            this.showTooltip = false;
            this.tooltipTimer = 0;
            runOnStopHover();
        }
    }

    private void animate() {
        if (this.showingClicked) {
            if (!this.whileDown.isRunning()) {
                this.whileUp.end();
                this.whileDown.run();
            }
        } else if (!this.whileUp.isRunning()) {
            this.whileDown.end();
            this.whileUp.run();
        }
    }

    public boolean onClick(int button, Point p) {
        if (this.bounds.contains(p)) {
            runClick();
            return true;
        }
        return false;
    }

    public void runOnMissedClick() {
    }

    public boolean onMouseDown(int button, Point p) {
        if (this.bounds.contains(p)) {
            (App.getInstance().getMouseManager()).clickedObject = this;
            runMouseDown();
            this.showingClicked = true;
            return true;
        }
        return false;
    }

    public boolean onMouseUp(int button, Point p) {
        if ((App.getInstance().getMouseManager()).clickedObject == this)
            (App.getInstance().getMouseManager()).clickedObject = null;
        if (!this.bounds.contains(p))
            runOnMissedClick();
        if (this.showingClicked) {
            this.showingClicked = false;
            if (this.bounds.contains(p)) {
                runMouseUp();
                onClick(button, p);
                return true;
            }
            return false;
        }
        return false;
    }

    public void onType(KeyEvent e) {
    }

    public void onKeyPressed(KeyEvent e) {
    }

    public Animation getWhileUpAnim() {
        return this.whileUp;
    }

    public Animation getWhileDownAnim() {
        return this.whileDown;
    }

    public void setWhileUpAnim(Animation whileUp) {
        this.whileUp = whileUp;
    }

    public void setWhileDownAnim(Animation whileDown) {
        this.whileDown = whileDown;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM