有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Javafx鼠标点击事件,该事件将撤消上一次鼠标点击所做的操作

所以我现在有一个3x3的网格窗格,我在网格上的每个空间都添加了一个白色背景的窗格

我试图做到的是,如果用户点击其中一个空间,白色窗格将变为另一种颜色。然后,如果用户再次单击该空间,窗格将变回白色。如果再次单击,它将再次变为该颜色,依此类推

简而言之,一次点击会导致一个动作,下一次点击,以及点击后的动作会反转/撤销上一个动作

然而,我只能通过最初的点击来使用它。我想补充的其他东西都没用

@Override
public void handle(MouseEvent me) {
                if (me.getClickCount() == 1) {
                    pane.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));}

任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    如果它真的必须是一个窗格,您可以尝试编写一个自定义窗格,这将使您更容易控制其行为:

    class MyPane extends Pane{
        private Background standard, other;
    
        public MyPane(){
            standard = new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY));
            other = new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY));
            this.setBackground(standard);
        }
    
        public void changeColor(){
            if(this.getBackground().equals(standard){
                this.setBackground(other);
            else{
                this.setBackground(standard);
            }
        }
    
        public void setBackground(Background bckgrnd){
            this.other = bckgrnd;
    }
    

    如果使用此类而不是标准窗格,则可以通过

    @Override
    public void  handle(MouseEvent me){
        myPane.changeColor();
    }
    

    如果要使用Rectangle类,可以使用以下代码:

    @Override
    public void handle(MouseEvent me){
        if(rectangle.getFill() == standard){
            rectangle.setFill(other);
        }else{
            rectangle.setFill(standard);
        }
    

    假设您定义了两个绘制变量standardother,例如:

    private final Paint standard = Color.WHITE;
    private Paint other = Color.RED;
    

    Color