如何在JavaFX中使用按钮来更改行的大小

时间:2016-12-24 16:11:18

标签: button javafx

我想用一个按钮来改变一行的大小,所以稍后我可以让这条线看起来像旋转......这是我到目前为止的代码:

package JavaFXApplication14;

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class JavaFXApplication14 extends Application 
{
    public static void main(String[] args) 
    {
        launch(args);
    }

    int x = 200;

    @Override public void start(Stage primaryStage) throws Exception 
    {
        final GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER); 
        grid.setHgap(100);
        grid.setVgap(100);
        grid.setPadding(new Insets(10, 10, 10, 10));

        Scene scene = new Scene(grid, 600, 400); //Color.BLACK ?
        primaryStage.setScene(scene);
        primaryStage.setTitle("4D");
        primaryStage.show();

        Line ln = new Line(100, 200, x, 200); 
        ln.setStroke(Color.BLUE);
        ln.setStrokeWidth(5);
        grid.add(ln, 0, 0);

        Button btn = new Button("X-Y");
        grid.setHalignment(btn, HPos.CENTER);
        btn.setOnAction(e -> btn_Click());
        grid.add(btn, 0, 1);
    }

    public void btn_Click()
    {
        x = x + 50;
    }
}

此外,有时当我使用以下代码行时,背景的颜色不会改变。

Scene scene = new Scene(grid, 600, 400, Color.BLACK);

这是什么原因?

1 个答案:

答案 0 :(得分:0)

按钮效果非常好,您可以对其进行测试,但在此处您只需将新值设置为x,而不是其他任何内容,换句话说,您不会更新您的位置x2 Line。您可以通过使变量ln可访问并更新其值EndX来表明这一点:

//before the method start
Line ln;
//Inside your btn_click() method add
ln.setEndX(x);

但它只会增加线条的大小(水平)而不会旋转它。通过一些研究解释here并按照我在评论中告诉你的内容,你可以根据旋转轴(startX& startY)和要旋转的点轻松完成(endX& endY):

public class Launcher extends Application{

private Pane root = new Pane();
private Scene scene;
private Button btn = new Button("Test");
private Line line;

@Override
public void start(Stage stage) throws Exception {

    line = new Line(200,200,200,100);
    line.setStroke(Color.BLACK);
    line.setStrokeWidth(5);  
    btn.setOnAction(e -> rotate()); 
    root.getChildren().addAll(btn,line);
    scene = new Scene(root,500,500);
    stage.setScene(scene);
    stage.show();

}


private void rotate(){


    double x1 = line.getEndX() - line.getStartX();
    double y1 = line.getEndY() - line.getStartY();

    //The more you reduce the angle the longer the rotation
    double x2 = x1 * Math.cos(0.1) - y1 * Math.sin(0.1); 
    double y2 = x1 * Math.sin(0.1) + y1 * Math.cos(0.1);

    line.setEndX(x2+ line.getStartX());
    line.setEndY(y2+ line.getStartY()); 

}


  public static void main(String[] args) {

    launch(args); 

  }
}

注意:在您的示例中,您使用了GridPane,因此您将无法正常运行,祝您好运!