JavaFX - 在条件语句中使用切换isSelected()

时间:2016-04-22 17:19:30

标签: if-statement netbeans radio-button toggle javafx-8

我正在使用JavaFX构建一个简单的草图程序。我希望用户能够在绘制矩形,圆形或直线之间切换,并且我已经在菜单中为这些选项设置了切换单选按钮。

是否可以编写if / else语句,以便根据选择的内容编写三种不同函数的代码?目前它只会绘制线条。到目前为止,这是我的代码的一部分(对不起它很乱):

package Sketchbook;



public class Sketchbook extends Application {

final static int CANVAS_WIDTH = 800;
final static int CANVAS_HEIGHT = 600;

ColorPicker colorPicker1;
ColorPicker colorPicker2;


@Override

public void start(final Stage primaryStage) {

final Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
initDraw(graphicsContext);

canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, 
new EventHandler<MouseEvent>(){

@Override
public void handle(MouseEvent event) {
graphicsContext.beginPath();
graphicsContext.moveTo(event.getX(), event.getY());
graphicsContext.setStroke(colorPicker1.getValue());
graphicsContext.stroke();
}
});

canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
graphicsContext.lineTo(event.getX(), event.getY());
graphicsContext.setStroke(colorPicker1.getValue());
graphicsContext.stroke();
}
});

canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, 
new EventHandler<MouseEvent>(){

@Override
public void handle(MouseEvent event) {

}
});       

Group root = new Group();

ToggleGroup toggleGroup = new ToggleGroup();
RadioButton rectangle = new RadioButton("Rectangle");
RadioButton circle = new RadioButton("Circle");
RadioButton line = new RadioButton("Line");
rectangle.setSelected(true);
rectangle.setToggleGroup(toggleGroup);
circle.setToggleGroup(toggleGroup);
line.setToggleGroup(toggleGroup);

1 个答案:

答案 0 :(得分:1)

您已经描述了您需要做的事情:

canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 

    new EventHandler<MouseEvent>(){

        @Override
        public void handle(MouseEvent event) {
            if (toggleGroup.getSelectedToggle() == line) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.setStroke(colorPicker1.getValue());
                graphicsContext.stroke();
            } else if (toggleGroup.getSelectedToggle() == rectangle) {
                // etc...
            } // etc...

        }
    }
});

显然,您可能需要对代码进行一些重新排序,以确保在使用它们之前声明和初始化变量。