簡體   English   中英

java - 如何在按鈕上獲得鼠標按下事件

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

我正在用 Java 創建一個程序,並且想制作自己的按鈕類而不是使用 JButton。 我已經整理出了所有的美學,但我不確定如何在 Java 中獲得鼠標按下事件。 這是我的代碼:

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

按下鼠標時布爾mouseDown將設置為true ,然后釋放時設置為false但是我找不到捕獲這些事件的方法,當我嘗試實現它時mouseListener會給出有關需要抽象類的錯誤。 感謝你給與我的幫助。

完整代碼

嘗試這個。

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...");
    } 

  }
});

查看可用方法

希望這有幫助!

您可以將偵聽器添加到處理事件的按鈕。

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;

     }
  }
});

我知道這個問題已經有幾年的歷史了,但考慮到我在自定義 UI 方面有一些經驗,我認為我的輸入可能對嘗試完成相同任務的人有用。

如果您想要一個完全非 JComponent 的按鈕,那么您還需要對鼠標偵聽器和 UI 對象注冊表和渲染/更新函數進行編程,所有這些都在它們所需的線程上運行。 我已經完成了,包括 NumberInputFields、Buttons、PasswordFields、TextFields、TextAreas、Graphics 和各種其他 UI 對象。 你不想這樣做,除非你想要一個完全不同的外觀和感覺,而不是已經提供了非常不同的功能(例如,我的 TextArea 和 TextField 采用由 TextBits 而不是 Strings 組成的 BitLines,這允許每個字符可以單獨設置格式、顏色或大小,並帶有自定義的懸停和單擊事件)。 如果需要這種不同的結果,您最好查看在 Canvas 對象中制作完整 UI 的所有內容。 如果沒有,您還有其他幾個選擇。

選項 1:像已經建議的那樣擴展 JButton 類。 這是最簡單的,可能是您的最佳選擇。 這相當簡單,您可以使該按鈕成為您想要的任何東西(當然,在合理范圍內)。

選項 2:通過擴展 BasicLookAndFeel 類創建您自己的自定義外觀。 這更復雜,可能需要一些時間和研究,但最終您可以格式化所有程序以使 L&F 始終保持一致,從而為您的軟件提供令人滿意且獨特的外觀。

下面是一個示例,說明如何制作具有基本功能的按鈕,完全獨立於 JComponent 類。 請注意,這不包括進行此操作所需的許多背景類,例如注冊表、渲染器、動畫和圖像加載器、偵聽器等。

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