How do I add an array of colored squares to JavaFX?

时间:2016-02-12 19:45:30

标签: java graphics javafx javafx-8

I need to display some information in JavaFX as a grid of colored squares. Here are some restrictions that I would prefer to be met: - Click events. I think this means each would have to be a node? Unless a node can get the coordinates of the click. - The squares to be ajacent, with no gaps. - Outlining a particular square. - If the array of squares is over a certain size, allow for scrolling. - Resizing of all the squares.

Any help on these would be greatly appreciated. I've been using Swing for the past few years, and I have to un-learn a whole bunch of stuff and I'm still figuring out how to draw custom components and such.

1 个答案:

答案 0 :(得分:0)

您可以使用GridPane。但是为了给不同的“单元格”着色,你必须向它添加节点(afaik)。

Gridpane上的Mouse事件为您提供了大量信息(基本上只是您想要的):

MouseEvent [source = Grid hgap=0.0, vgap=0.0, alignment=TOP_LEFT, target = Grid hgap=0.0, vgap=0.0, alignment=TOP_LEFT, eventType = MOUSE_CLICKED, consumed = false, x = 110.0, y = 52.0, z = 0.0, button = PRIMARY, pickResult = PickResult [node = Grid hgap=0.0, vgap=0.0, alignment=TOP_LEFT, point = Point3D [x = 110.0, y = 52.0, z = 0.0], distance = 724.0178566683622]

但是,如果只是将事件处理程序添加到“单元格”中的不同节点,则代码将更容易阅读。

我确定您也可以根据需要调整TableView,并且可能不需要为节点填充节点(与网格视图一样)。

要让不同的节点具有不同的颜色,只需将所需的StyleClass添加到节点

即可
object.getStyleClass().add("redCell");

并在css中设置样式

.redCell {
    -fx-background-color: #123456;
}

然而,通常我应该先问你已经尝试过什么,因为这不是一个平台,可以让开发者“怎样做x”并获得“这种方式”。它通常是“我试过这个,但它不起作用,我应该尝试下一步/我做错了什么?” :)