下面列出了怎么用javafx.scene.shape.Rectangle的API类实例代码及写法,或者点击链接到github查看源代码。
public Node toNode() {
Vector screenSize = viewport.getSizeSC();
if (screenSize.equals(currentScreenSize))
return microscope;
currentScreenSize = screenSize;
double minScreenSize = Math.min(screenSize.x, screenSize.y);
double maxScreenSize = Math.max(screenSize.x, screenSize.y);
// Leave an ample left/bottom black margin - otherwise, the background
// will be visible for a moment while enlarging the window.
Rectangle black = new Rectangle(-10, -10, maxScreenSize + 1000, maxScreenSize + 1000);
Circle hole = new Circle(screenSize.x / 2, screenSize.y / 2, minScreenSize / 2.03);
microscope = Shape.subtract(black, hole);
microscope.setEffect(new BoxBlur(5, 5, 1));
return microscope;
}
public StrokeTransitionSample() {
super(150,150);
Rectangle rect = new Rectangle(0, 0, 150, 150);
rect.setArcHeight(20);
rect.setArcWidth(20);
rect.setFill(null);
rect.setStroke(Color.DODGERBLUE);
rect.setStrokeWidth(10);
getChildren().add(rect);
strokeTransition = StrokeTransitionBuilder.create()
.duration(Duration.seconds(3))
.shape(rect)
.fromValue(Color.RED)
.toValue(Color.DODGERBLUE)
.cycleCount(Timeline.INDEFINITE)
.autoReverse(true)
.build();
}
public ScaleTransitionSample() {
super(150,150);
Rectangle rect = new Rectangle(50, 50, 50, 50);
rect.setArcHeight(15);
rect.setArcWidth(15);
rect.setFill(Color.ORANGE);
getChildren().add(rect);
scaleTransition = ScaleTransitionBuilder.create()
.node(rect)
.duration(Duration.seconds(4))
.toX(3)
.toY(3)
.cycleCount(Timeline.INDEFINITE)
.autoReverse(true)
.build();
}
@Spawns("Tower")
public Entity spawnTower(SpawnData data) {
TowerDataComponent towerComponent = new TowerDataComponent();
// try {
// towerComponent = getAssetLoader()
// .loadKV("Tower" + data.get("index") + ".kv")
// .to(TowerDataComponent.class);
//
// } catch (Exception e) {
// throw new RuntimeException("Failed to parse KV file: " + e);
// }
return entityBuilder()
.type(TowerDefenseType.TOWER)
.from(data)
.view(new Rectangle(40, 40, data.get("color")))
.with(new CollidableComponent(true), towerComponent)
.with(new TowerComponent())
.build();
}
protected void setNodeSize(final Node node, final double x, final double y, final double width, final double height) {
node.setLayoutX(x);
node.setLayoutY(y);
// TODO find generic way to set width and height of any node
// here we cannot set height and width to node directly.
if (node instanceof Canvas) {
((Canvas) node).setWidth(width);
((Canvas) node).setHeight(height);
} else if (node instanceof Rectangle) {
((Rectangle) node).setWidth(width);
((Rectangle) node).setHeight(height);
} else if (node instanceof Region) {
((Region) node).setPrefWidth(width);
((Region) node).setPrefHeight(height);
}
}
public MenuBox(int width, int height) {
Rectangle bg = new Rectangle(width, height);
bg.setFill(Colors.MENU_BG);
Rectangle lineTop = new Rectangle(width, 2);
lineTop.setFill(Colors.MENU_BORDER);
lineTop.setStroke(Color.BLACK);
Rectangle lineBot = new Rectangle(width, 2);
lineBot.setTranslateY(height - 2);
lineBot.setFill(Colors.MENU_BORDER);
lineBot.setStroke(Color.BLACK);
box = new VBox(5);
box.setTranslateX(25);
box.setTranslateY(25);
getChildren().addAll(bg, lineTop, lineBot, box);
}
private void initGraphics() {
if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 ||
Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) {
if (getPrefWidth() > 0 && getPrefHeight() > 0) {
setPrefSize(getPrefWidth(), getPrefHeight());
} else {
setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
nameText = new Text(getName());
nameText.setTextOrigin(VPos.TOP);
valueText = new Text(String.format(locale, formatString, getValue()));
valueText.setTextOrigin(VPos.TOP);
barBackground = new Rectangle();
bar = new Rectangle();
pane = new Pane(nameText, valueText, barBackground, bar);
pane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
getChildren().setAll(pane);
}
public ChartItem(final ChartData CHART_DATA, final CtxBounds CONTENT_BOUNDS, final String FORMAT_STRING) {
chartData = CHART_DATA;
contentBounds = CONTENT_BOUNDS;
title = new Label(chartData.getName());
value = new Label(String.format(Locale.US, FORMAT_STRING, chartData.getValue()));
scale = new Rectangle(0, 0);
bar = new Rectangle(0, 0);
formatString = FORMAT_STRING;
step = PREF_WIDTH / (CHART_DATA.getMaxValue() - CHART_DATA.getMinValue());
compressed = false;
chartDataListener = e -> {
switch(e.getType()) {
case UPDATE : update(); break;
case FINISHED: update(); break;
}
};
initGraphics();
registerListeners();
}
public RotateTransitionSample() {
super(140,140);
Rectangle rect = new Rectangle(20, 20, 100, 100);
rect.setArcHeight(20);
rect.setArcWidth(20);
rect.setFill(Color.ORANGE);
getChildren().add(rect);
rotateTransition = RotateTransitionBuilder.create()
.node(rect)
.duration(Duration.seconds(4))
.fromAngle(0)
.toAngle(720)
.cycleCount(Timeline.INDEFINITE)
.autoReverse(true)
.build();
}
@Override
public Node apply(Region region, Wrapper<Point2D> mouseLocation) {
final DoubleProperty xProperty = region.layoutXProperty();
final DoubleProperty yProperty = region.layoutYProperty();
final Rectangle resizeHandleNW = new Rectangle(handleRadius, handleRadius, Color.BLACK);
resizeHandleNW.xProperty().bind(xProperty.subtract(handleRadius / 2));
resizeHandleNW.yProperty().bind(yProperty.subtract(handleRadius / 2));
setUpDragging(resizeHandleNW, mouseLocation, Cursor.NW_RESIZE);
resizeHandleNW.setOnMouseDragged(event -> {
if(mouseLocation.value != null) {
dragNorth(event, mouseLocation, region, handleRadius);
dragWest(event, mouseLocation, region, handleRadius);
mouseLocation.value = new Point2D(event.getSceneX(), event.getSceneY());
}
});
return resizeHandleNW;
}
private void initGraphics() {
if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 ||
Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) {
if (getPrefWidth() > 0 && getPrefHeight() > 0) {
setPrefSize(getPrefWidth(), getPrefHeight());
} else {
setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
nameText = new Text(getName());
nameText.setTextOrigin(VPos.TOP);
valueText = new Text(String.format(locale, formatString, getValue()));
valueText.setTextOrigin(VPos.TOP);
barBackground = new Rectangle();
bar = new Rectangle();
pane = new Pane(nameText, valueText, barBackground, bar);
pane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
getChildren().setAll(pane);
}
private Parent createContent() {
Pane root = new Pane();
root.setPrefSize(300, 300);
Rectangle bg = new Rectangle(300, 300);
ToggleSwitch toggle = new ToggleSwitch();
toggle.setTranslateX(100);
toggle.setTranslateY(100);
Text text = new Text();
text.setFont(Font.font(18));
text.setFill(Color.WHITE);
text.setTranslateX(100);
text.setTranslateY(200);
text.textProperty().bind(Bindings.when(toggle.switchedOnProperty()).then("ON").otherwise("OFF"));
root.getChildren().addAll(toggle, text);
return root;
}
@Spawns("projectile")
public Entity newProjectile(SpawnData data) {
var view = new Rectangle(30, 3, Color.LIGHTBLUE);
view.setStroke(Color.WHITE);
view.setArcWidth(15);
view.setArcHeight(10);
return entityBuilder()
.type(EntityType.PROJECTILE)
.from(data)
.viewWithBBox(view)
.collidable()
.zIndex(-5)
.with(new ProjectileComponent(new Point2D(1, 0), 760))
.build();
}
private Node createLoadPane() {
loadPane = new TilePane(5, 5);
loadPane.setPrefColumns(3);
loadPane.setPadding(new Insets(5));
for (int i = 0; i < 9; i++) {
StackPane waitingPane = new StackPane();
Rectangle background = new Rectangle((380) / 3, (380) / 3,
Color.WHITE);
indicators[i] = new ProgressIndicator();
indicators[i].setPrefSize(50, 50);
indicators[i].setMaxSize(50, 50);
indicators[i].setTranslateY(-25);
indicators[i].setTranslateX(-10);
loading[i] = new Label();
loading[i].setTranslateY(25);
waitingPane.getChildren().addAll(background, indicators[i],
loading[i]);
loadPane.getChildren().add(waitingPane);
}
return loadPane;
}
public FillTransitionSample() {
super(100,100);
Rectangle rect = new Rectangle(0, 0, 100, 100);
rect.setArcHeight(20);
rect.setArcWidth(20);
rect.setFill(Color.DODGERBLUE);
getChildren().add(rect);
fillTransition = FillTransitionBuilder.create()
.duration(Duration.seconds(3))
.shape(rect)
.fromValue(Color.RED)
.toValue(Color.DODGERBLUE)
.cycleCount(Timeline.INDEFINITE)
.autoReverse(true)
.build();
}
public void generate() {
for (int i=0; i<STAR_COUNT; i++) {
int hex = 0;
int randColor = RandomUtil.getRandomInt(31);
if (randColor == 0)
hex = 0xe7420b; // red orange
else if (randColor == 1)
hex = 0xd0d0f9; // light blue
else if (randColor == 2)
hex = 0xf4df0d; // FFFFE0; // yellow
else
hex = 0xffffff; // white
if (hex != 0xffffff) {
int rand = RandomUtil.getRandomInt(127);
hex = hex + rand;
}
String hexString = Integer.toHexString(hex);
Color c = Color.web(hexString, 1.0);
nodes[i] = new Rectangle(1, 1, c);
angles[i] = 2.0 * Math.PI * random.nextDouble();
//start[i] = random.nextInt(2000000000);
start[i] = random.nextInt(2000000000);
}
}
public SpaceLevel() {
Rectangle bg = new Rectangle(getAppWidth() - 20, 200, Color.color(0, 0, 0, 0.6));
bg.setArcWidth(25);
bg.setArcHeight(25);
bg.setStroke(Color.color(0.1, 0.2, 0.86, 0.76));
bg.setStrokeWidth(3);
storyPane.setTranslateX(10);
storyPane.setTranslateY(25);
rootPane = new Pane(bg, storyPane);
rootPane.setTranslateX(10);
rootPane.setTranslateY(getAppHeight() - 200);
}
public TutorialSubScene() {
var textTutorial = getUIFactoryService().newText("Tap the circle to change ball color\n\n" +
"Tap the left side of the screen to move left!\n\n" +
"Tap the right side of the screen to move right!", Color.WHITE, FontType.TEXT, 20);
textTutorial.setWrappingWidth(250);
textTutorial.setTextAlignment(TextAlignment.LEFT);
var bg = new Rectangle(300, 230, Color.color(0.3627451f, 0.3627451f, 0.5627451f, 0.55));
bg.setArcWidth(50);
bg.setArcHeight(50);
bg.setStroke(Color.WHITE);
bg.setStrokeWidth(10);
var stackPane = new StackPane(bg, textTutorial);
getContentRoot().setTranslateX(-250);
getContentRoot().setTranslateY(250);
getContentRoot().getChildren().add(stackPane);
getTimer().runOnceAfter(() -> {
animationBuilder()
.onFinished(() -> getSceneService().popSubScene())
.interpolator(Interpolators.EXPONENTIAL.EASE_IN())
.translate(getContentRoot())
.from(new Point2D(50, 250))
.to(new Point2D(-250, 250))
.buildAndPlay(TutorialSubScene.this);
}, Duration.seconds(0.5));
}
/**
* Helper method that creates and styles a POV object.
*
* The POV object is a styled rectangle that is used to indicate the
* currently observed time range (aka time extent) on the timeline. It can
* also be used to quickly interact with the time extent.
*
* @return A formatted POV object.
*/
private Rectangle createPOV() {
final Rectangle rect = new Rectangle(135, 25, 60, 1);
// Bind the height of the POV to the Height of the histogram:
rect.yProperty().bind(histogram.heightProperty());
rect.heightProperty().bind(innerPane.prefHeightProperty());
rect.setManaged(true);
// Style the rectangle:
rect.setStroke(Color.DODGERBLUE);
rect.setStrokeWidth(2d);
final LinearGradient gradient
= new LinearGradient(0.0, 0.0, 0.0, 0.5, true, CycleMethod.NO_CYCLE, new Stop[]{
new Stop(0, Color.LIGHTBLUE.darker()),
new Stop(1, Color.TRANSPARENT)
});
rect.setFill(gradient);
rect.setSmooth(true);
// Round the edges of the rectangle:
rect.setArcWidth(5.0);
rect.setArcHeight(5.0);
// Set the POV mouse event handlers:
final POVMouseEventHandler handler = new POVMouseEventHandler(rect);
rect.setOnMouseMoved(handler);
rect.setOnMousePressed(handler);
rect.setOnMouseDragged(handler);
rect.setOnMouseReleased(handler);
// Make the POV object the top-most object on this panel:
rect.toFront();
return rect;
}
public static Group createRectangle(Color color, double tx, double ty, double sx, double sy) {
Group squareGroup = new Group();
Rectangle squareShape = new Rectangle(1.0, 1.0);
squareShape.setFill(color);
squareShape.setTranslateX(-0.5);
squareShape.setTranslateY(-0.5);
squareGroup.getChildren().add(squareShape);
squareGroup.setTranslateX(tx);
squareGroup.setTranslateY(ty);
squareGroup.setScaleX(sx);
squareGroup.setScaleY(sy);
return squareGroup;
}
private Shape makeSquare(Color colour, Color border) {
Stop[] stops = new Stop[]{new Stop(0, colour), new Stop(0.95, colour.deriveColor(1, 1, .75, 1)), new Stop(1.0, colour.deriveColor(1, 1, 0.5, 1))};
LinearGradient gradient = new LinearGradient(0, 0, 0, 1, true, CycleMethod.NO_CYCLE, stops);
Rectangle square = new Rectangle(SQUARE_SIZE, SQUARE_SIZE);
square.setStroke(border);
square.setFill(gradient);
return square;
}
@Spawns("block")
public Entity newBlock(SpawnData data) {
return FXGL.entityBuilder()
.at(data.getX(), data.getY())
.type(ScifiType.PLATFORM)
.viewWithBBox(new Rectangle(640 - 512, 64, Color.DARKCYAN))
.zIndex(10000)
.with(new PhysicsComponent())
.build();
}
private void initGraphics() {
if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 || Double.compare(getWidth(), 0.0) <= 0 ||
Double.compare(getHeight(), 0.0) <= 0) {
if (getPrefWidth() > 0 && getPrefHeight() > 0) {
setPrefSize(getPrefWidth(), getPrefHeight());
} else {
setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
axisCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT);
axisCtx = axisCanvas.getGraphicsContext2D();
Color selectionRectColor = getSelectionRectColor();
rect = new Rectangle();
rect.setMouseTransparent(true);
rect.setVisible(false);
rect.setStroke(Helper.getColorWithOpacity(selectionRectColor, 0.5));
rect.setFill(Helper.getColorWithOpacity(selectionRectColor, 0.25));
connectionCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT);
connectionCanvas.setMouseTransparent(true);
connectionCtx = connectionCanvas.getGraphicsContext2D();
connectionCtx.setTextAlign(TextAlignment.LEFT);
connectionCtx.setTextBaseline(VPos.CENTER);
dragText = new Text("");
dragText.setVisible(false);
dragText.setTextOrigin(VPos.CENTER);
dragText.setFill(Helper.getColorWithOpacity(getHeaderColor(), 0.5));
getChildren().setAll(axisCanvas, rect, connectionCanvas, dragText);
}
@Override
public void initialize(final URL location, final ResourceBundle resources) {
canvasPane.setPrefWidth(canvas.getPrefWidth());
canvasPane.setPrefHeight(canvas.getPrefHeight());
canvas.scaleXProperty().addListener(obs -> {
canvasPane.setPrefWidth(canvas.getPrefWidth() * canvas.getScaleX());
canvasPane.setTranslateX((canvasPane.getPrefWidth() * canvas.getScaleX() - canvasPane.getPrefWidth()) / 2d);
});
canvas.scaleYProperty().addListener(obs -> {
canvasPane.setPrefHeight(canvas.getPrefHeight() * canvas.getScaleY());
canvasPane.setTranslateY((canvasPane.getPrefHeight() * canvas.getScaleY() - canvasPane.getPrefHeight()) / 2d);
});
// Because several instruments are not bound to an FXML widget, have to call the initialization here.
textSetter.initialize(null, null);
meta.initialize(null, null);
canvas.clipProperty().bind(Bindings.createObjectBinding(() -> {
final double zoom = canvas.getScaleX();
final double hmin = scrollPane.getHmin();
final double vmin = scrollPane.getVmin();
final double contentWidth = canvasPane.getPrefWidth() / zoom;
final double contentHeight = canvasPane.getPrefHeight() / zoom;
final double vpWidth = scrollPane.getViewportBounds().getWidth() / zoom;
final double vpHeight = scrollPane.getViewportBounds().getHeight() / zoom;
final double x = Math.max(0d, contentWidth - vpWidth) * (scrollPane.getHvalue() - hmin) / (scrollPane.getHmax() - hmin);
final double y = Math.max(0d, contentHeight - vpHeight) * (scrollPane.getVvalue() - vmin) / (scrollPane.getVmax() - vmin);
return new Rectangle(x, y, vpWidth, vpHeight);
}, scrollPane.vvalueProperty(), scrollPane.hvalueProperty(), scrollPane.viewportBoundsProperty()));
setActivated(true);
}
public void updateClippingArea(UIRectangle childArea) {
UIRectangle bounds = this.getBounds();
UIRectangle area = new UIRectangle();
area.getPosition().setX(childArea.getX() - bounds.getX());
area.getPosition().setY(childArea.getY() - bounds.getY());
area.getSize().setWidth(childArea.getWidth());
area.getSize().setHeight(childArea.getHeight());
this.getControl().setClip(new Rectangle(area.getX(), area.getY(), area.getWidth(), area.getHeight()));
}
/** Create a car an place it in the pane */
private void drawCar() {
getChildren().clear();
rectangle = new Rectangle(x, y - 20, 50, 10);
polygon = new Polygon(x + 10, y - 20, x + 20, y - 30, x + 30,
y - 30, x + 40, y - 20);
circle1 = new Circle(x + 15, y - 5, radius);
circle2 = new Circle(x + 35, y - 5, radius);
getChildren().addAll(rectangle, circle1, circle2, polygon);
}
@Test
public void fastVisibleIndexTest() {
ObservableList<Rectangle> items = FXCollections.observableArrayList();
for (int i = 0; i < 100; i++) {
items.add(new Rectangle(500, 100));
}
VirtualFlow<Rectangle, Cell<Rectangle, Rectangle>> vf = VirtualFlow.createVertical(items, Cell::wrapNode);
vf.resize(100, 450); // size of VirtualFlow enough to show several cells
vf.layout();
ObservableList<Cell<Rectangle,Rectangle>> visibleCells = vf.visibleCells();
vf.show(0);
vf.layout();
assertSame(visibleCells.get(0), vf.getCell(vf.getFirstVisibleIndex()));
assertSame(visibleCells.get(visibleCells.size() - 1), vf.getCell(vf.getLastVisibleIndex()));
assertTrue(vf.getFirstVisibleIndex() <= 0 && 0 <= vf.getLastVisibleIndex());
vf.show(50);
vf.layout();
assertSame(visibleCells.get(0), vf.getCell(vf.getFirstVisibleIndex()));
assertSame(visibleCells.get(visibleCells.size() - 1), vf.getCell(vf.getLastVisibleIndex()));
assertTrue(vf.getFirstVisibleIndex() <= 50 && 50 <= vf.getLastVisibleIndex());
vf.show(99);
vf.layout();
assertSame(visibleCells.get(0), vf.getCell(vf.getFirstVisibleIndex()));
assertSame(visibleCells.get(visibleCells.size() - 1), vf.getCell(vf.getLastVisibleIndex()));
assertTrue(vf.getFirstVisibleIndex() <= 99 && 99 <= vf.getLastVisibleIndex());
}
public MenuButton(String name) {
text = new Text(name);
text.setFont(text.getFont().font(20));
text.setFill(Color.WHITE);
Rectangle bg = new Rectangle(250, 30);
bg.setOpacity(0.6);
bg.setFill(Color.BLACK);
bg.setEffect(new GaussianBlur(3.5));
setAlignment(Pos.CENTER_LEFT);
setRotate(-0.5);
getChildren().addAll(bg, text);
setOnMouseEntered(event -> {
bg.setTranslateX(10);
text.setTranslateX(10);
bg.setFill(Color.WHITE);
text.setFill(Color.BLACK);
});
setOnMouseExited(event -> {
bg.setTranslateX(0);
text.setTranslateX(0);
bg.setFill(Color.BLACK);
text.setFill(Color.WHITE);
});
DropShadow drop = new DropShadow(50, Color.WHITE);
drop.setInput(new Glow());
setOnMousePressed(event -> setEffect(drop));
setOnMouseReleased(event -> setEffect(null));
}
private List<Rectangle> processCodeAreas(Parent pane) {
var nodes = pane.lookupAll("ContentEditor");
ArrayList<Rectangle> result = new ArrayList<>();
for (Node node : nodes) {
ArrayList<TextBoundingBox> bboxes = new ArrayList<>();
var area = ((ContentEditor) node).getCodeArea();
LiveList<Paragraph<Collection<String>, String, Collection<String>>> visibleParagraphs = area.getVisibleParagraphs();
int visibleParIdx = 0;
for (Paragraph visiblePar : visibleParagraphs) {
int parIdx = area.visibleParToAllParIndex(visibleParIdx);
var parMatcher = tagPattern.matcher(visiblePar.getText());
if (parMatcher.find()){
// var bounds = area.getVisibleParagraphBoundsOnScreen(visibleParIdx);
var matchStartIdxAbs = area.getAbsolutePosition(parIdx, parMatcher.start());
var bounds = area.getCharacterBoundsOnScreen(matchStartIdxAbs, matchStartIdxAbs + parMatcher.group().length());
bounds.ifPresent(b -> {
var localBounds = parent.sceneToLocal(area.localToScene(area.screenToLocal(b)));
bboxes.add(new TextBoundingBox(parMatcher.group(1),
localBounds.getMinX(), localBounds.getMinY(), localBounds.getWidth(), localBounds.getHeight()));
});
}
visibleParIdx++;
}
var rectangles = getRectangles(area, bboxes);
if (rectangles.size() > 0){
result.addAll(rectangles);
boxes.put(area, rectangles);
}
}
return result;
}
/**
* creates empty drawers stack
*/
public JFXDrawersStack() {
final Rectangle clip = new Rectangle();
clip.widthProperty().bind(this.widthProperty());
clip.heightProperty().bind(this.heightProperty());
this.setClip(clip);
}