JavaFX 在鼠标按下时改变圆圈的颜色

标签 java javafx colors action shapes

我正在使用 JavaFX 为学校开发一个简单的应用程序。我们应该制作一个白色圆圈,当按下鼠标按钮时,该圆圈会变成黑色,然后在释放鼠标按钮时变回白色。对于我的一生,我找不到我在这里出错的地方。该代码在 Eclipse 中编译良好,没有警告/错误,并给我一个空白的白色窗口。我确信这很简单,但我盯着它看了这么久,却错过了它。任何帮助深表感谢。代码如下:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import javafx.scene.layout.StackPane;


public class CircleColor extends Application {
    private CirclePane circlePane = new CirclePane();

    @Override // Override the start method in the Application class.
    public void start(Stage primaryStage) {     
        Pane pane = new Pane();

        // Handle mouse click actions.
        circlePane.setOnMousePressed(e -> { 
            circlePane.paintBlack();
        });

        // Handle mouse release actions.
        circlePane.setOnMouseReleased(e -> {
            circlePane.paintWhite();
        });

        // Create a scene & place it on the stage.
        Scene scene = new Scene(pane, 200, 200);
        primaryStage.setTitle("CircleColor"); // Set the stage title.
        primaryStage.setScene(scene); // Place the scene on the stage.
        primaryStage.show(); // Display the stage.

        circlePane.requestFocus();


    } // Close the start method.


    // Main method only needed for IDEs with limited JavaFX support
    public static void main(String[] args) {
        launch(args);

    } // Close the main method.

} // Close CircleColor class


class CirclePane extends StackPane {
    private Circle circle = new Circle(50);

    public CirclePane() {
        getChildren().add(circle);
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.WHITE);
    } // Close CirclePane constructor.

    public void paintBlack() {
        circle.setFill(Color.BLACK);
    } // Close the paintBlack method.

    public void paintWhite() {
        circle.setFill(Color.WHITE);
    } // Close the paintWhite method.

} // Close the CirclePane class.

最佳答案

您永远不会将 CirclePane 添加到场景中。

因此,不要使用 new Scene(pane,200,200); 尝试 new Scene(circlePane,200,200);

关于JavaFX 在鼠标按下时改变圆圈的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33340835/

相关文章:

java - 到底什么是链接(符号或其他)

java - 使用 JDK 9.0.1 安装 NetBeans 8.0.2

arrays - 用二维数组填充表格 View

java - JavaFX 是否有办法创建分组堆积条形图?

javascript - HTML & Js 颜色选择器 : What am I doing wrong?

iphone - 检测 iPhone/iPod 颜色

c# - 如何检查两个 System.Drawing.Color 结构是否以 16 位色深表示相同的颜色?

java - 拆分使用 .返回 0

java - CopyOnArrayList 并发修改

java - 有没有办法将我所有重复的 VBox 重新组织到自定义 JavaFX 标签中?